Ruby code: why put a colon before the variable name (inside the initialization method)

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

Is there a reason for colon?

attr_reader :var1, :var2

def initialize(var1:, var2:)
   @var1 = var1
   @var2 = var2
end
+4
source share
2 answers

These are keyword arguments.

You can use them by name, not position. For instance.

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

or

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

Article about keyword arguments with mousebot

+3
source

It is called keyword arguments .

The keyword arguments are similar to the default positional arguments of the value:

def add_values(first: 1, second: 2)
  first + second
end

Keyword arguments will be accepted with **:

def gather_arguments(first: nil, **rest)
  p first, rest
end


gather_arguments first: 1, second: 2, third: 3
# prints 1 then {:second=>2, :third=>3}

. Error .

.

+4

Source: https://habr.com/ru/post/1659706/


All Articles