chopper draw lion4
chopper draw lion4

Reputation: 13487

How do if statements return values?

I am trying to shift all letters to the right one while excluding non-letters. This operation seems so simple I can't wrap my head around why this is not returning me values + 1. I come from Python background and new to Ruby, if I am making a very obvious mistake please forgive me.

def rotate(letter_num)
    if letter_num + 1 == 123
      return 97
    elsif letter_num + 1 == 91
      return 65
    elsif !(letter_num =~ /[a-zA-Z]/)
      return letter_num
    else
      return letter_num + 1
    end
end

Example 1: Actual result:

rotate(60)
=> 60

Expected result:

rotate(60)
=> 61

Example 2:

Actual result:

rotate(123)
=> 123

Expected result:

rotate(123)
=> 97

Upvotes: 0

Views: 58

Answers (1)

Chuck
Chuck

Reputation: 237060

This doesn't really have to do with how if-expressions work. What's happening is that the expression !(letter_num =~ /[a-zA-Z]/) is true for all of those numbers (because they are numbers rather than strings that contain letters), so you're hitting the return letter_num line every time.

Upvotes: 1

Related Questions