Ruby: Conditional return and Conditional assignments

Conditional Assignments

Type : 1

# If a is already set, then leave as it is,
# but if a is nil then assign it with 13
ROR: 126 > a = 12
 O/P => 12 
ROR: 127 > a ||= 13
 O/P => 12
# If a is not already set, then assign it with 13
 ROR: 128 > a = nil
 O/P => nil
 ROR: 129 > a ||= 13
 O/P => 13

Type 2:

# While assigning a to be, is a is not set then 12 is assigned to b
ROR: 130 > a = 1
 O/P => 1 
ROR: 131 > b = a || 12
 O/P => 1
# While assigning a to b, is a is not set then 13 is assigned to b
ROR: 132 > a = nil 
 O/P => nil 
ROR: 133 > b = a || 13
 O/P => 13

Conditional Returns

def method(arg = nil)
  # do something
  return arg || 'Default String'
end
  
ROR: 138 > method
 O/P => "Default String"
def method(arg = nil)
  # do something
  return arg || 'Default String'
end
  
ROR: 138 > method(12)
 O/P => 12

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s