What does colon after a parameter in ruby mean?

Viewed 4372

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

1 Answers

While calling that function/Constructor you no 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 arguments order.

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/

Related