1

I have a method in a model with Rails. This is the code:

def ensure_appropriate_age
  age = match[:age]

  if age[/\d/].to_i > 18
    current_user.update age: age[/\d/].to_i
  else
    %{We could not proceed, sorry.}
  end
end

I'm taking the input of what the user types and if it contains a number, verify that it is greater than 18 to store it.

I'll enter my age like so: im 24. I still get false, and I can see in the database it's only storing the number "2".

What is required to make this work?

2 Answers 2

4

You have to use \d+ to match multiple digits; \d only matches a single digit in a number.

You can also capture the value of the regex into a variable, so that you don't have to evaluate it twice, like shown:

def ensure_appropriate_age(age_string)
  age = age_string[/\d+/].to_i

  if age > 18
    current_user.update age: age
  else
    %{We could not proceed, sorry.}
  end
end
Sign up to request clarification or add additional context in comments.

Comments

1

It's good to step back a second, and ask yourself why do you need to extract the age from a string here. What else are you holding in it? If more information is present, build a quick parser in the caller or initializer to partition the data, and cast to the proper types.

The trick is: once the age is isolated from the other information, casting is straightforward.

user_data = "John Smith 22"
@name, @surname, age_str = user_data.split(" ")
@age = age_str.to_i

Then just use your function. Ruby style guides also advise you to use quotes "..."rather than
%{} unless needed (i.e. your string is full of quotes).

If you push yourself to keep it simple whenever you can, you will find your code easier to read and faster to write and debug. There's plenty cases in which regex(es?) are the simplest way to go, but until you get there don't sweat it :)

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.