Understanding Ruby method parameters syntax

2019-03-02 02:02发布

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

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

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?

1条回答
Bombasti
2楼-- · 2019-03-02 02:34

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

查看更多
登录 后发表回答