Wednesday 1 June 2016

Ruby - Assignment concept


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  


Practice the above mentioned statements in irb.

Hope you like this.

Thank you

No comments:

Post a Comment

My Experience in RUBYCONF INDIA 2016

Hi Readers, Rubyconf India is a global event complementing other RubyConf events across the world. I attended this event held on 19-20 ma...