Postazure
Postazure

Reputation: 33

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?

Upvotes: 0

Views: 418

Answers (4)

tijko
tijko

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.google.com/url?sa=t&source=web&rct=j&opi=89978449&url=https://stackoverflow.com/questions/7557382/understanding-ruby-splat-in-ranges-and-arrays&ved=2ahUKEwiryaSc9t6IAxXLKlkFHVdgKXgQFnoECBwQAQ&usg=AOvVaw25PetbGCi5C-lBMQfXEaTA

https://www.rubyinrails.com/2019/07/10/ruby-splat-operator-for-arguments/

https://codeburst.io/splat-8993c3270eef

Upvotes: 0

Marko Krstic
Marko Krstic

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

Simone Carletti
Simone Carletti

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:

  • In Ruby you use implicit return
  • In Ruby naming is underscore_case
  • No need for a variable there

Upvotes: 4

rorofromfrance
rorofromfrance

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

Related Questions