rubyrange

Return Range Ruby


def myRange
  this_range = [0..3]
  return this_range
end

puts myRange
puts rand(myRange)
Mac:Postazure$ ruby TESTER.rb
0..3
TESTER.rb:7:in `rand': no implicit conversion of Array into Integer (TypeError)
    from TESTER.rb:7:in `<main>'

This returns a Range of '0..3' but it can't be used as above. Any ideas how I might get that to work?


Solution

  • [0..3] doesn't return a Range. It returns an Array with one Range element.

    2.1.1 :001 > [0..3].class
     => Array 
    

    To return a Range, change the code to

    def myRange
      this_range = 0..3
      return this_range
    end
    
    myRange.class
     => Range 
    

    or even better

    def my_range
      0..3
    end
    

    Then you can call

    puts rand(myRange)
    

    Coding style notes: