Search code examples
rubyinstance-variables

ruby or operator behaving differently inside initialise method


fairly new to programming and came across the following code which does gives the intended result, that is it stores the object in the instance variable if passed as an argumnet or defaults to generating a new object and storing that. but the syntax is using an or(||) operator which as i understood always returns a boolean. so is it behaving differently or there is more to or/and operators?

def initialize(args = {})`
 @sms = args[:sms]              || Messenger.new
end

Solution

  • The or operator in ruby does not "return" a boolean: it evalutes to the first expression if the first expression is truthy (a term which means everything but false and nil), otherwise it evalutes to the latter

    5 || nil => 5
    nil || 5 => 5
    false || nil => nil
    nil || false => false