Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does colon after a parameter in ruby mean?

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

like image 951
Aalya Banu Avatar asked Dec 05 '25 08:12

Aalya Banu


1 Answers

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/

like image 114
Ashik Ali Avatar answered Dec 06 '25 22:12

Ashik Ali