Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUBY

ruby ||=

# a ||= b is a conditional assignment operator. It means:
# if a is undefined or falsey, then evaluate b and set a to the result.
# otherwise (if a is defined and evaluates to truthy), then b is not evaluated, and no assignment takes place.

a ||= nil      # => nil
a ||= 0        # => 0
a ||= 2        # => 0

# It can be useful in some memoization scenarios
def current_user
  @current_user ||= User.find_by_id(session[:user_id])
end

# it can be problematic with boolean values

foo = false 	# => false
foo ||= true 	# => true      <-- false have been a valid value 
foo ||= false 	# => true

# Send an email to the user (unintended bugs when used with boolean values)
#
# @param [String] use_ses - use AWS SES to send the email.
#                           when testing locally, set this value to false
def send_email(use_ses = nil)
  use_ses ||= true

  puts 'email sent successfully' if use_ses
end

send_email
# => email sent successfully

send_email(true)
# => email sent successfully

send_email(false)
# This is a bug
# => email sent successfully
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #ruby
ADD COMMENT
Topic
Name
3+4 =