0

So let's say I have an array of strings in C#, I could convert this array of strings to an array of integers using the following LINQ statement:

(new[] {"1", "2", "3"}).Select(x => int.parse(x))

Is there a Ruby equivalent to this?

James
  • 680
  • 2
  • 8
  • 22

2 Answers2

1

Not quite sure what Select means in C#, but converting an array of strings to array of integers is quite simple: ["1", "2", "3"].map(&method(:Integer))

Victor Moroz
  • 9,167
  • 1
  • 19
  • 23
  • Ah, so .map is used for data transformation then. I had seen that used one at some point didn't get a real understanding of what was happening, but now it makes perfect sense. Thanks for the help. – James Sep 04 '12 at 16:22
  • I realize this is an old post, but @Victor `Select` is C#'s version of `map`. It's named that way to imitate SQL and reduce the cognitive dissonance when you switch back and forth between the two. – Chris Pfohl Dec 27 '12 at 16:27
  • @James, the other really important ruby sequence method is `filter` (for C#'s `Where`). In all the ruby methods you can use any callable as the parameter like a proc or lambda, just like in C#, but the syntax is a bit wonkier (on the other hand, creating an inline array in C# is quite wonky). – Chris Pfohl Dec 27 '12 at 16:29
1

A more shorter solution:

["1", "2", "3"].map(&:to_i)
Mik
  • 4,117
  • 1
  • 25
  • 32