0

I have the following function

def getValue(x) 
    puts "Key: #{x}"
    if x =~ /[0-9]+/
        puts "x is an int"
    else
        puts "x is a string"
    end
end

On getValue(1) it should output "x is an int" but instead I get "x is a string"

3
  • Why not just write puts x.class = #{x.class}"? Commented Nov 27, 2014 at 20:10
  • @CarySwoveland my goal is to run some expression of x is an int and another expression if x is a string Commented Nov 27, 2014 at 20:14
  • That's a different question, whose answer could be case x; when Fixnum then process_fixnum(x); when String then process_string(x); when Float... end. Commented Nov 27, 2014 at 20:17

3 Answers 3

3

The left-hand expression must be a String to use the =~ operator with a regular expression. Call to_s on x before testing against the regular expression:

def getValue(x) 
    puts "Key: #{x}"
    if x.to_s =~ /[0-9]+/
        puts "x is an int"
    else
        puts "x is a string"
    end
end

Also, method names in Ruby are snake_case, so getValue should be get_value.

Or you could just use x.is_a? Integer if you want to check the type of the value, not the string representation.

Regex advise: As Michael Berkowski mentioned, your regular expression will match a string that has a digit anywhere. You should anchor the pattern between \A (start of string) and \Z (end of string):

\A[0-9]+\Z

Even more nit-picking: the [0-9] character class is equivalent to the \d meta character, so you could do this as well:

\A\d+\Z
Sign up to request clarification or add additional context in comments.

1 Comment

Also recommend anchoring the pattern with ^$ because it would also match notanumber99notanumber as /[0-9]+/
3

Use is_a? to inspect the type:

def getValue(x) 
    puts "Key: #{x}"
    if x.is_a?(Integer)
        puts "x is an int"
    else
        puts "x is a string"
    end
end

Output:

irb> getValue(1)
Key: 1
x is an int
irb> getValue("1")
Key: 1
x is a string

1 Comment

Rigid type checking is generally frowned upon in Ruby.
0

You might want to test if it can be converted to an integer, not if it is one:

def get_value(x)
  puts "Key: #{x}"

  # This throws an ArgumentError exception if the value cannot be converted
  Integer(x)

  puts "x is an int"

rescue ArgumentError
  puts "x is not an integer"
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.