Reputation: 33
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?
Upvotes: 0
Views: 418
Reputation: 8292
You could use the splat operator (*
) on the array return itself. In Ruby a single splat operator can be used to destructure an array.
So something like:
def myRange
this_range = [0..3]
return this_range
end
puts myRange
puts rand(*myRange)
Would do the trick for what you're trying to accomplish here.
Some links for further reading:
https://www.rubyinrails.com/2019/07/10/ruby-splat-operator-for-arguments/
https://codeburst.io/splat-8993c3270eef
Upvotes: 0
Reputation: 1447
Yes, because you used an array instead of a range.
Try something like this:
def myRange
this_range = 0..3
return this_range
end
puts myRange
puts rand(myRange)
Upvotes: 1
Reputation: 176382
[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:
Upvotes: 4
Reputation: 1904
Try this instead (1..3)
not [1..3]
and it should work :)
def myRange
this_range = (0..3)
return this_range
end
puts rand(myRange)
#==> 2
Upvotes: 0