belgoros
belgoros

Reputation: 3928

Ruby: Convert String to Integer values of a nested array

I can't figure out why the following expression does not convert Strings to Integers:

[["1", "2"], ["10", "20"]].each {|sr| sr.map(&:to_i)}
=> [["1", "2"], ["10", "20"]]

So, instead of getting a nested array of integer numbers I'm still getting the same String values. Any idea ?

Thank you.

uSer Ruby version: 2.6.1

Upvotes: 0

Views: 487

Answers (4)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121020

While the answer by @MarekLipka perfectly sheds a light on the issue in pure ruby, I am here to shamelessly promote my gem iteraptor:

[["1", "2"], ["10", "20"]].
  iteraptor.
  map { |_key, value| value.to_i }
#⇒ [[1, 2], [10, 20]]

or, if you like Spanish:

[["1", "2"], ["10", "20"]].mapa { |_, value| value.to_i }
#⇒ [[1, 2], [10, 20]]

It would work with arrays of any depth:

[[["1", "2"], ["3"]], [[[[["10"]]]], "20"]].
  mapa { |_key, value| value.to_i }
#⇒ [[[1, 2], [3]], [[[[[10]]]], 20]]

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51191

It's because you're using each, which returns original array. Use map instead:

[["1", "2"], ["10", "20"]].map { |sr| sr.map(&:to_i) }
# => [[1, 2], [10, 20]]

You can also use map!, which modifies an array instead of returning a new one, like this:

[["1", "2"], ["10", "20"]].each { |sr| sr.map!(&:to_i) }
# => [[1, 2], [10, 20]]

It depends on what you want, obviously.

Upvotes: 6

Jose Manuel
Jose Manuel

Reputation: 183

If you change it to [["1", "2"], ["10", "20"]].map { |sr| sr.map(&:to_i) } you'll get the integer values.

Upvotes: 0

Rajagopalan
Rajagopalan

Reputation: 6064

Use this code

p [["1", "2"], ["10", "20"]].map{|x,y|[x.to_i,y.to_i]}

Output

[[1, 2], [10, 20]]

Upvotes: 0

Related Questions