Dave
Dave

Reputation: 19250

Getting "TypeError: no implicit conversion of Regexp into Integer" when trying to extract number from string

I'm using Rails 5. I'm having an issue extracting the numeric portion of a field and inserting it into my model attribute. I have

  puts "age:#{age}"
  self.age = age[/\d+/].present? ? age[/\d+/].to_i : nil

But I'm getting the output

age:41
TypeError: no implicit conversion of Regexp into Integer
    from /Users/davea/Documents/workspace/myproject/app/models/my_object_time.rb:129:in `[]'
    from /Users/davea/Documents/workspace/myproject/app/models/my_object_time.rb:129:in `set_age'
    from /Users/davea/Documents/workspace/myproject/app/models/my_object_time.rb:51:in `block in <class:RaceTime>'

Is there a better way to write the above to extract the number (if ther eis one) but also avoid the error I'm seeing?

Upvotes: 1

Views: 2931

Answers (3)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369556

The error message is telling you that the [] you are calling expects an Integer as an argument, and thus it tries to convert the Regexp to an Integer (by calling to_int) but fails because Regexps don't respond to to_int.

Since String#[] does take a Regexp as an argument, it's obvious that the object referenced by age cannot be a String, it must be something else. Unfortunately, you don't tell us what object it is (you really should include such information in your question!) but we can make an educated guess: there are only three [] methods in Ruby I can think of, which would conceivably raise this exact error: Array#[], MatchData#[], and Integer#[]. So, my best guess at this point is that your age object is actually not a String, but rather a MatchData object, an Array, or an Integer.

But, we can do better: you included the result of to_s in your question. Array#to_s returns something like '[1, 2, 3]', but your question shows that age.to_s returns something like '41'. So, it can't be an Array.

Ergo, age is either a MatchData object or an Integer, but you are expecting it to be a String. You need to figure out where age is coming from, and why it isn't what you expect it to be, then fix that.

Upvotes: 2

DjezzzL
DjezzzL

Reputation: 845

I think you should better write that like:

str = "sometext 123 sometext"
self.age = /(?<age>\d+)/ =~ str.to_s ? age.to_i : nil

Upvotes: 0

max pleaner
max pleaner

Reputation: 26778

Your age variable is probably a number. I get the same error when I try to use the [/regex/] method with a number:

[5] pry(main)> 1[//]
TypeError: no implicit conversion of Regexp into Integer

You could say age = age.to_s first

Upvotes: 0

Related Questions