Monday 6 June 2016

Case statements, Blocks and String operations

Hi Readers,

Today we are going to learn how to write case statements in Ruby. Know about ruby blocks and some string operations with examples.

Case:

    x = 11 
    case x 
    when 0 
    when 1, 2..5 
      puts "Second branch" 
    when 6..10 
      puts "Third branch" 
    when *[11, 12] 
      puts "Fourth branch" 
    when String: puts "Fifth branch" 
    when /\d+\.\d+/ 
      puts "Sixth branch" 
    when x.to_s.downcase == "peter" 
      puts "Seventh branch" 
    else 
      puts "Eight branch" 
    end   

Blocks - Usage examples:

    # Iteration 
    [1, 2, 3].each { |item| puts item } 
     
    # Resource Management 
    File.open("file.txt", "w") do |file| 
      file.puts "foobar" 
    end 
     
    # Callbacks 
    widget.on_button_press do 
      puts "Got button press" 
    end 
     
    # Convention: one-line blocks use {...} and multiline 
    # blocks use do...end  

Common String Operations:

    "  ".empty? == true 
    IO.read(__FILE__).each_with_index { |line, i| puts "#{i}: #{line}" } 
    "abc".scan(/./).each { |char| char.upcase } 
    "we split words".split.join(", ") 
    "    strip space   ".strip 
    sprintf("value of %s is %.2f", "PI", 3.1416) 
    "I Go Ruby"[2, 2] == "I Go Ruby"[2..3] # => "Go"   

Hope you will understand this concepts. Next we will meet with different concept.
Please practice these to get hands on experience.

Share if you like else comment.

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...