filmnut filmnut - 1 month ago 9
Ruby Question

Using Ruby's `or` Keyword When Creating a Variable

I recently came across the following Ruby code, which is confusing me:

def initialize(kind, street_1, street_2, city, state, postal_code)
@kind = kind or ''
@street_1 = street_1 or ''
@street_2 = street_2 or ''
@city = city or ''
@state = state or ''
@postal_code = postal_code or ''
end


I don't understand what role
or
is playing in this code. Can someone please explain?

Answer

EDIT: It should be noted that the or keyword does not work in this scenario, but the intention is correct - using || instead of or in this example will produce the desired output.

The or keyword in this code implies that if the parameter being assigned to the local variable (i.e. kind and @kind respectively) is nil, then the value of the local variable should be initialized to ''

Another way to look at this - if I call Class.new("something", "1800 Wallaby Way", nil, nil, nil, nil), then the class will be initialized as such:

@kind = "something"
@street_1 = "1800 Wallaby Way"
@street_2 = ''
@city = '
@state = ''
@postal_code = ''