了解Ruby方法参数的语法 [英] Understanding Ruby method parameters syntax

查看:49
本文介绍了了解Ruby方法参数的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在遵循有关Pluralsight的RSpec教程来创建基本的纸牌游戏.当这样定义类时:

I've been following an RSpec tutorial on Pluralsight for creating a basic card game. When the class is defined as such:

class Card
  def initialize(suit:, rank:)
    @suit = suit
    @rank =
      case rank
      when :jack then 11
      when :queen then 12
      when :king then 13
      else rank
      end
  end
end

RSpec测试代码例如:

the RSpec test code is for example:

RSpec.describe 'a playing card' do
  it 'has a suit' do
    raise unless Card.new(suit: :spades, rank: 4).suit == :spades
  end
end

我没有遇到像(suit: :spades, rank: 4)这样的方法参数语法.有人可以解释一下这是什么意思,或者向我指出在哪里查找的正确方向吗?

I haven't encountered method parameter syntax like this (suit: :spades, rank: 4). Can someone explain what this means, or point me in the right direction on where to look this up?

推荐答案

它称为关键字参数.与位置参数不同,您可以以任何顺序传递它们,但必须提供它们的名称.这可以大大提高可读性,尤其是对于具有较高Arity的方法. 有关此主题的更多信息

It's called keyword arguments. Unlike positional arguments, you can pass them in any order, but you have to provide their names. This can greatly improve readability, especially for methods with higher arity. More on the subject

这篇关于了解Ruby方法参数的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆