Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby code: why put colon in front of variable name (inside initialize method)

Tags:

ruby

I came across some Ruby code, I try to understand why the variables have colon at the end of their name inside the declaration of the initialize method.

Is there any reason for the colon?

attr_reader :var1, :var2

def initialize(var1:, var2:)
   @var1 = var1
   @var2 = var2
end
like image 556
FredyK Avatar asked Nov 03 '16 10:11

FredyK


1 Answers

Those are keyword arguments.

You can use them by name and not position. E.g.

ThatClass.new(var1: 42, var2: "foo")

or

ThatClass.new(var2: "foo", var1: 42)

An article about keyword arguments by thoughtbot

like image 189
Ursus Avatar answered Oct 02 '22 15:10

Ursus