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 ''
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.
or keyword in this code implies that if the parameter being assigned to the local variable (i.e.
@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 = ''