Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Ranges in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 327
    Comment on it

    In modern programming world, ruby is so much popular because of its easability and general purpose syntaxes. Ranges are yet another example of that feature. They store the start and end of a sequence and rest are assumed to be inside them. Ranges can be inclusive or exclusive, in inclusive you need to put two dots in the range and in exclusive you need to write 3 dots in the range like this:

    (1..6) => 1,2,3,4,5,6  #inclusive
    (1...6) => 1,2,3,4,5   #exclusive
    
    a = (1..5)
    

    Here a is a range object. Now this range can be used in several places. Some of them are:

    1) Retrieve all the elements of a range:

    >   a = (1..5)
     => 1..5
    > a.to_a # To get all elements
     => [1, 2, 3, 4, 5]

    2) It also supports some of the array type methods of ruby like:

    > a.min # To get minimum element in the range
     => 1
    > a.max # To get maximum element in the range
     => 5
    > a.include?(4) # To check whether an element comes in range or not
     => true
    

    3) Inside conditions

    Ranges can also be used inside condition like:

    case some_value
      when 0..1000 then "Low"
      when 1001..5000 then "High"
      when 5001..10000 then "Great"
      else "Extraordinary"
    end

    4) As an interval:

    Ranges can also be used as an interval, suppose some value comes in a range and we want to do something in that case, "===" operator can be used for that:

    if (('a'..'m') === 'c')
      puts "c is in the range"
    end
    


    Hope you liked reading this blog. I will come back soon with more topics on rails.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: