[ruby koans] about_keyword_arguments 键值对参数

Learn Ruby with the edgecase ruby koans

about_keyword_arguments 键值对参数

键值对参数

  • 方法中用键来访问对应的参数,参数可以有缺省值

  • 没有缺省值的参数,必须传参,否则会抛出 ArgumentError

  def method_with_keyword_arguments(one: 1, two: 'two')
    [one, two]
  end
​
  def test_keyword_arguments
    assert_equal Array, method_with_keyword_arguments.class
    assert_equal [1, 'two'], method_with_keyword_arguments
    assert_equal ['one','two'], method_with_keyword_arguments(one: 'one')
    assert_equal [1, 2], method_with_keyword_arguments(two: 2)
  end
​
  def method_with_keyword_arguments_with_mandatory_argument(one, two: 2, three: 3)
    [one, two, three]
  end
​
  def test_keyword_arguments_with_wrong_number_of_arguments
    exception = assert_raise (ArgumentError) do
      method_with_keyword_arguments_with_mandatory_argument
    end
    assert_match(/given 0, expected 1/, exception.message)
  end

[Think about it] Keyword arguments always have a default value, making them optional to the caller

建议所有的 keyword 参数 都有缺省值,对调用者来说,这些参数就是可选的

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值