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?

Mas Bagol
  • 4,377
  • 10
  • 44
  • 72
  • 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}` – 7stud Sep 20 '14 at 16:37
  • @7stud another way with `each`. `[1,2,3,4].to_enum(:map).each { |x| x + 1 }` -> `[2, 3, 4, 5]` – Roman Kiselenko Sep 20 '14 at 16:50

1 Answers1

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()

Community
  • 1
  • 1
Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103