vellur
vellur

Reputation: 13

Ruby if-statement with strings always go to first case (not rails)

I'm quite new to Ruby. So I have a method that takes string input and then compares it several times. The problem is - no matter what - it always go to the first case. For example:

def method (s)
    if s <=> "help"
        help()
    elsif s <=> "add"
        puts"Enter 2 numbers"
        a = STDIN.gets
        b = STDIN.gets
        add(a,b)
    else
        err("Invalid command, type 'help' for list of available commands")
    end
end

class.method(STDIN.gets)

always do "help()", no matter what the input is. How it should be written?

Upvotes: 1

Views: 179

Answers (2)

SERGHII
SERGHII

Reputation: 64

Comparison operator(<=>) on String: Returns -1, 0, +1 or nil depending on whether a string is less than, equal to, or greater than other_string. nil is returned if the two values are incomparable. All of the returning values (-1, 0, +1) are truthy in ruby. So what you wrote is equal to

if true
  help ()
else
  ....
end

Upvotes: 0

Greg
Greg

Reputation: 6648

<=> is useful for ordering, it'll give you 0 when strings are equal, -1 when s is before "help" (in a dictionary sense) and 1 otherwise.

Why not use == there?:

if s == "help"
    help()
elsif s == "add"
    puts"Enter 2 numbers"
    a = STDIN.gets
    b = STDIN.gets
    add(a,b)
else
    err("Invalid command, type 'help' for list of available commands")
end

Or to clean it up a bit:

case s
when "help":
  help()
when "add":
  puts"Enter 2 numbers"
  a = STDIN.gets
  b = STDIN.gets
  add(a,b)
else
  err("Invalid command, type 'help' for list of available commands")
end

Case is perfectly communicating the intent there.

Upvotes: 2

Related Questions