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

2

I'm starting to study programming so, it's a very beginner question.

I tested 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

All was well until I tried to explore the code a little more, displaying warnings for times greater than 90 or less than -1 and then everything stopped.

Follow the problem code

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 in 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

If someone knows how to help, thank you in advance!

    
asked by anonymous 19.02.2018 / 19:37

2 answers

3

I do not understand much of ruby, but for a quick read I believe it is for escaping the comparison to infinity, both negative and positive.

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

And to escape to positive, use the final output of the else, and do another 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 the fiddle: HERE

References:

Ruby range: operators in case statement

Infinity in Ruby

    
19.02.2018 / 20:25
3

The response from @AnthraxisBR works fine, but I'd like to extend it by explaining why it works.

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

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

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

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

By inspecting what === does in Range , I have found that it does call the include? method. It is written in C.

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

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

    
17.03.2018 / 14:26