微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby 参数后面的冒号是什么意思?

如何解决ruby 参数后面的冒号是什么意思?

我试图理解下面写的代码。初始化方法中参数后的冒号是什么意思?像 consumable: account: 等。我理解在变量名前有一个冒号意味着它是一个符号,不能像变量一样改变它的值。但是后面有一个冒号是什么意思?谢谢

class Purchaser
  attr_accessor :consumable,:account,:amount,:reason
  def initialize(consumable:,account:,amount:,reason:)
    @consumable = consumable
    @account = account
    @amount = amount
    @reason = reason
  end

  def make_purchase
    if purchase.update(account: account,amount: amount,reason: reason) && decrease_stock
      return true
    else
      return false
  end

解决方法

在调用该函数/构造函数时,您无需遵循顺序,您可以通过提及变量关键字来更改顺序。因此我们可以避免混淆而不是盲目记住参数顺序。

例如。

#This will work
Purchaser.new(consumable:"yes",account:"Normal",amount:"10",reason:"Credit")

#this will also work
Purchaser.new(account:"Normal",reason:"Credit",consumable:"yes") 

了解更多信息。查看使用关键字参数提高清晰度部分 https://www.rubyguides.com/2018/06/rubys-method-arguments/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。