seasonalz
seasonalz

Reputation: 61

Comparing a rand to a range of numbers?

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?

Upvotes: 1

Views: 92

Answers (4)

iGian
iGian

Reputation: 11183

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

Upvotes: 0

Stefan
Stefan

Reputation: 114168

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)

Upvotes: 5

max
max

Reputation: 101976

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

irb(main):001:0> (0..9).cover?(0.1)
=> true

Upvotes: 3

Rajagopalan
Rajagopalan

Reputation: 6064

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

Upvotes: 1

Related Questions