0

i want to convert numbers from regex to integer. I don’t know how to explain it clearly (my English is bad). So, I’ll go with an example:

regex      = /data:\s*(\d+(?:\s*,\s*\d+)*)/i
string     = "Data: 1, 2, 3, 4"
data       = string.match(regex)
split_data = data[1].split(", ")
int_data1  = split_data.each {|i|i = i.to_i}
int_data2  = [1, 2, 3, 4]
p int_data1, int_data2

# int_data1 => ["1", "2", "3", "4"]
# int_data2 => [1, 2, 3, 4]

I expected int_data1 to return [1, 2, 3, 4], but it can't be converted to integer. So, it keeps return me ["1", "2", "3", "4"].

Is something I do wrong?

2
  • 2
    each() returns the original array. So to use each(), you would have to do something like this: int_data1 = []; split_data.each {|str| int_data << str.to_i} Commented Sep 20, 2014 at 16:37
  • @7stud another way with each. [1,2,3,4].to_enum(:map).each { |x| x + 1 } -> [2, 3, 4, 5] Commented Sep 20, 2014 at 16:50

1 Answer 1

1

This:

int_data1 = split_data.each { |i| i = i.to_i }

Should be:

int_data1 = split_data.map { |i| i.to_i }

Or more short syntax:

int_data1 = split_data.map(&:to_i)

Read about difference between .each() and .map()

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.