简体   繁体   English

了解Ruby方法参数语法

[英]Understanding Ruby method parameters syntax

I've been following an RSpec tutorial on Pluralsight for creating a basic card game. 我一直在关注有关Pluralsight的RSpec教程,以创建基本的纸牌游戏。 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

the RSpec test code is for example: RSpec测试代码例如:

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

I haven't encountered method parameter syntax like this (suit: :spades, rank: 4) . 我还没有遇到这样的方法参数语法(suit: :spades, rank: 4) Can someone explain what this means, or point me in the right direction on where to look this up? 有人可以解释一下这是什么意思,或向我指出在哪里查找的正确方向吗?

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. 这可以大大提高可读性,尤其是对于具有较高Arity的方法。 More on the subject 有关此主题的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM