Hi Readers,
Today we are going learn assignment of a variable value in ruby.
Assignment:
- a, b = b, a # swapping values
- a = 1; b = 1
- a = b = 1
- a += 1 # a = a + 1
- a, b = [1, 2]
- a = b || c
- a ||= b
Idiom: Assignment with Boolean Expression
comment = Object.new
def comment.user
Object.new
end
# Overly verbose:
user_id = nil
if comment
if comment.user
user_id = comment.user.object_id
end
end
# Idiomatic:
user_id = comment && comment.user && comment.user.object_id
def comment.user
Object.new
end
# Overly verbose:
user_id = nil
if comment
if comment.user
user_id = comment.user.object_id
end
end
# Idiomatic:
user_id = comment && comment.user && comment.user.object_id
Practice the above mentioned statements in irb.
Hope you like this.
Thank you
No comments:
Post a Comment