filmnut filmnut - 10 months ago 48
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 ''

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

Answer Source

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"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 = ''