Monday 6 June 2016

Ruby Range class, Structs and Exceptions

Hi readers,

In this post we are going to know about Range class, Structs in ruby and exceptions.

Range Class:

    # Two dots is inclusive, i.e. 1 to 5 
    (1..5).each { |x| puts x**2 }  
     
    # Three dots excludes the last item, i.e. 1 to 4 
    (1...5).each { |x| puts x } 
     
    (1..3).to_a == [1, 2, 3]  

Structs:

    Rating = Struct.new(:name, :ratings)  
    rating = Rating.new("Rails", [ 10, 10, 9.5, 10 ])  
     
    puts rating.name 
    puts rating.ratings  

Exceptions:

    begin  
      raise(ArgumentError, "No file_name provided") if !file_name 
      content = load_blog_data(file_name) 
      raise "Content is nil" if !content  
    rescue BlogDataNotFound  
      STDERR.puts "File #{file_name} not found"  
    rescue BlogDataConnectError 
      @connect_tries ||= 1 
      @connect_tries += 1 
      retry if @connect_tries < 3  
      STDERR.puts "Invalid blog data in #{file_name}"  
    rescue Exception => exc  
      STDERR.puts "Error loading #{file_name}: #{exc.message}" 
      raise 
    end  


Just can you practice above examples, then you will understand the concept, otherwise place comment on it.

Thank you share with your friends.

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