Ruby on rails ruby中参数后面的冒号是什么意思?

Ruby on rails ruby中参数后面的冒号是什么意思?,ruby-on-rails,ruby,colon,Ruby On Rails,Ruby,Colon,我试图理解下面写的代码。initialize方法中参数后面的冒号是什么意思?比如:account:等等。我知道变量名前面有冒号意味着它是一个符号,不能像变量那样改变它的值。但是后面有一个冒号意味着什么呢?谢谢 class Purchaser attr_accessor :consumable, :account, :amount, :reason def initialize(consumable:, account:, amount:, reason:) @consumable

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

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

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


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

比如说

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

#this will also work
Purchaser.new(account:"Normal", amount:"10", reason:"Credit",consumable:"yes") 
了解更多信息。查看部分使用关键字参数以提高清晰度

仅添加-将其定义为
耗材:
而不是
耗材:“一些默认值”
意味着
耗材是必需的参数。是。你说得对。在声明函数时。