Ruby - comparison of values between a range or greater than, less than

Asked

Viewed 663 times

2

I’m starting to study programming so, here’s a good beginner question.

I took the test below to learn about case in Ruby,

current_time = ARGV.first.to_i

case current_time
when 0..45 then puts('First Haf')
when 46..90 then puts('Second Haf')
else puts('Invalid Time')
end

Everything was going well until I tried to explore the code a little more, displaying warnings for times longer than 90 or less than -1 and then it all stopped.

Follow the code that gave problem

current_time = ARGV.first.to_i

case current_time
when 0..45 then puts('First Haf')
when 46..90 then puts('Second Haf')
when > 91 then puts('Overtime')
when < -1 then puts('Game not started')
else puts('Invalid Time')
end

The message displayed on the console is

ruby case2-range-tempo-futebol.rb 91
case2-range-tempo-futebol.rb:6: syntax error, unexpected '>'
when > 91 then puts('Overtime')
      ^
case2-range-tempo-futebol.rb:7: syntax error, unexpected keyword_when, expecting end-of-input
when < -1 then puts('Game not star

In case anyone knows how to help, I’d like to thank you!

2 answers

4

The response of @Anthraxisbr works well, but I’d like to extend it explaining why it works.

The comparison when > 10 does not work because an expression needs two sides. The when expects a value to compare, not the comparator itself.

The idea of using a Range is fantastic and works great when you need to compare if a value is between a range. And it works because the Range implements the method ===, called case Equality.

Open the IRB and test expressions using the case Equality. You will have to:

irb(main):001:0> (1..10) === 5
=> true
irb(main):002:0> (1..10) === 11
=> false

Inspecting what the === does in the Range, I’ve found that what he does is call the method include?. Is written in C.

range_eqq(VALUE range, VALUE val)
{
    return rb_funcall(range, rb_intern("include?"), 1, val);
}

You could say that Range#=== is an alias for Range#include?.

  • 1

    Thank you so much for the @vnbrs explanation!

3


I don’t know much about Ruby, but for a quick read I think it’s because I miss the comparison to infinity, both negative and positive.

The comparator -Float::INFINITY...0 seems to indicate to compare if the number is negative.

And to escape to positive, use the final exit of Else, and do one more if inside it, as in the example below:

tempo = -4
case tempo
when -Float::INFINITY...0 then puts 'Jogo nao iniciado'
when 0..45 then puts 'Primeiro tempo'
when 46..90 then puts 'Segundo tempo'
else 
  if tempo >= 91
    puts 'Tempo finalizado'
  else
    puts 'Tempo invalido'
  end
end

See working on fiddle: HERE

References:

Ruby range: Operators in case statement

Infinity in Ruby

  • Thank you very much Anthraxisbr! Thanks for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.