简体   繁体   中英

Understanding Ruby method parameters syntax

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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