Understanding Ruby method parameters syntax

你离开我真会死。 提交于 2019-12-02 11:17:24

问题


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:


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



来源:https://stackoverflow.com/questions/34827446/understanding-ruby-method-parameters-syntax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!