0

I have an array as below:

arr = [
  nil,
  6,
  "17 to 23 ||'.'||24 to 25 (add a decimal at 10th place)",
  nil,
  nil,
  "37 to 51 ||'.'||52 to 53 (add a decimal at 100th place)",
  nil
]

I want to convert this array into the following:

arr = [
  nil,
  6,
  "10th",
  nil,
  nil,
  "100th",
  nil
]

i.e from the string "17 to 23 ||'.'||24 to 25 (add a decimal at 10th place)", I need the digits mentioned in the bracket.

I tried the following code, but its not working:

arr.map! {|e| e[/^.*?add.*?(\d+)th.*?$/]}
2
  • Do you only have to match ...th? What about ...2nd and ...3rd? Commented Jan 5, 2017 at 10:34
  • i want to match th only Commented Jan 5, 2017 at 10:41

1 Answer 1

6

Your code fails because obj[pattern] only works for strings and not for nil or integers (there is Integer#[] but it does something else):

nil[/foo/] #=> NoMethodError: undefined method `[]' for nil:NilClass
123[/foo/] #=> TypeError: no implicit conversion of Regexp into Integer

You could use =~ instead which is defined on Object and overridden by subclasses, e.g. String:

arr.map {|e| e =~ /(\d+th)/ ? $1 : e }
#=> [nil, 6, "10th", nil, nil, "100th", nil]

If e matches /(\d+th)/, return $1 (the first capture group), otherwise e itself.

You can also use a more specific pattern:

/add a decimal at (\d+th) place/
Sign up to request clarification or add additional context in comments.

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.