Reputation: 191
I am trying to understand the code written below. What does a colon after the parameter in the initialize method mean? like consumable: account: etc. I understand having a colon before the variable name means it is a symbol and cannot change its value unlike variables. But what does having a colon after mean? Thanks
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
Upvotes: 18
Views: 11745
Reputation: 348
While calling that function/Constructor you do not need to follow the order and you can change the order by mentioning the variable keyword. Thus we can avoid confusion rather than blindly remembering the order of arguments.
For example.
#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")
For more information. Have look on the section Use Keyword Arguments to Increase Clarity https://www.rubyguides.com/2018/06/rubys-method-arguments/
Upvotes: 21