0

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

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, Marek, for pointing out to what each returns as well as to the difference if using the bang ! version of map in the block.
2

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]]

6 Comments

We know you, mudsie. "shamelessly" needn't be said.
The upvote is less for the answer and more because you decided to use the lambda symbol (λ) throughout your code base
@engineermnky lol github.com/am-kantox/transdeal we use it in prod.
@engineersmnky, I predict that many readers of your comment will henceforth incorporate "λ" in their answers, even when inappropriate.
@CarySwoveland is I were to bite my tongue for fear someone could misinterpret my meaning I'd dare not speak at all.
|
0

Use this code

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

Output

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

Comments

0

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

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.