1

Is there a function in Ruby that'll allow me to do what I'm attempting here?

rand1 = rand(10)

puts rand1
puts ""

if rand1 == (0..9)
  print "yes"
else
  print "no"
end

This prints out no, how could line 6 be altered so that this will print out yes?

seasonalz
  • 61
  • 7
  • Possible duplicate of [Determining if a variable is within range?](https://stackoverflow.com/questions/870507/determining-if-a-variable-is-within-range) – Viktor Oct 27 '19 at 09:57
  • It would be helpful if you could explain what, *exactly* is unclear to you about the documentation of `Range`. That way, the Ruby developers can improve the documentation so that future developers don't stumble across the same problems you did. Help make the world a better place! – Jörg W Mittag Oct 27 '19 at 10:32
  • @seasonalz : You are testing whether an object of class `Integer` is **equal** to an object of class `Range`.Of course you get false. An apple is not a pear. What do you want to achieve here? – user1934428 Oct 28 '19 at 10:31

4 Answers4

5

You could use a case expression:

case rand
when 0..9
  print 'yes'
else 
  print 'no'
end

It also allows you to provide multiple ranges or numbers to compare against. Here's a contrived example:

case rand
when 0..2, 3, 4..9
  print 'yes'
else 
  print 'no'
end

Under the hood, case uses === to compare the given objects, i.e. the above is (almost) equivalent to:

if 0..2 === rand || 3 === rand || 4..9 === rand
  print 'yes'
else
  print 'no'
end

(note that the when objects become the receiver and rand becomes the argument)

Stefan
  • 109,145
  • 14
  • 143
  • 218
3

You can use Range#cover? which works like === in this case.

irb(main):001:0> (0..9).cover?(0.1)
=> true
max
  • 96,212
  • 14
  • 104
  • 165
1

It's simple, use ===

rand1 = rand(10)

puts rand1
puts ""

if (0..9) === rand1
  print "yes"
else
  print "no"
end

Note: rand1===(0..9) won't work

And also you can use member?

rand1 = rand(10)

puts rand1
puts ""

if (0..9).member?(rand1)
  print "yes"
else
  print "no"
end
Rajagopalan
  • 5,465
  • 2
  • 11
  • 29
0

Not the best option but yet an option (not covered here: Determining if a variable is within range?)

rand1 >= (0..9).begin && rand1 <= (0..9).end

See Range docs, anyway: https://ruby-doc.org/core-2.6.5/Range.html#method-i-end

iGian
  • 11,023
  • 3
  • 21
  • 36