Forum: Ruby convert string array to interger array in in one line

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bdee3ba9491da0b6bc0f35dedb5b7a14?d=identicon&s=25 Jags Rao (jags)
on 2008-11-05 14:10
hi guys

i have a array like this for e.g

[["0", "0", "0", "0", "0", "3", "3"],
 ["0", "0", "0", "0", "0", "3", "3"],
 ["0", "0", "0", "0", "0", "3", "3"],
 ["0", "3", "0", "0", "0", "0", "3"],
 ["0", "0", "0", "0", "0", "0", "3"]]

how wud i convert to this

[[0, 0, 0, 0, 0, 3, 3],
 [0, 0, 0, 0, 0, 3, 3],
 [0, 0, 0, 0, 0, 3, 3],
 [0, 0, 0, 0, 0, 3, 3],
 [0, 0, 0, 0, 0, 0, 3],
 [0, 0, 0, 0, 0, 0, 3],
 [0, 3, 0, 0, 0, 0, 3],
 [0, 0, 0, 0, 0, 0, 3],

i.e a string array to integer array in 1 line if possible

pls help
C40020a47c6b625af6422b5b1302abaf?d=identicon&s=25 Stefano Crocco (crocco)
on 2008-11-05 14:16
(Received via mailing list)
Alle Wednesday 05 November 2008, Jags Rao ha scritto:
> how wud i convert to this
> i.e a string array to integer array in 1 line if possible
>
> pls help

a.map{|i| i.map{|s| s.to_i}}

Stefano
31fdda5f38fc6df4e193cfb7445ddc5a?d=identicon&s=25 RichardOnRails (Guest)
on 2008-11-05 22:45
(Received via mailing list)
On Nov 5, 8:08 am, Jags Rao <aquaj...@yahoo.com> wrote:
> how wud i convert to this
> i.e a string array to integer array in 1 line if possible
>
> pls help
> --
> Posted viahttp://www.ruby-forum.com/.

Maybe this is a little clearer:

aStrings = [["0", "0", "0", "0", "0", "3", "3"],
 ["0", "0", "0", "0", "0", "3", "3"],
 ["0", "0", "0", "0", "0", "3", "3"],
 ["0", "3", "0", "0", "0", "0", "3"],
 ["0", "0", "0", "0", "0", "0", "3"]]

aFixnums = aStrings.map{|i| i.map{|s| s.to_i}}
puts aStrings[0][0].class.to_s # => String
puts aFixnums[0][0].class.to_s # => Fixnum
puts aFixnums[0][0].integer?   # => true (So a Fixnum is_a Integer)

Note that the last line asserts that a Fixnum object is indeed an
Integer

HTH,
Richard
289cf19aa581c445915c072bf45c5e25?d=identicon&s=25 Todd Benson (Guest)
on 2008-11-05 23:49
(Received via mailing list)
On Wed, Nov 5, 2008 at 7:08 AM, Jags Rao <aquajags@yahoo.com> wrote:
> how wud i convert to this
> i.e a string array to integer array in 1 line if possible
Here's a weird one for your enjoyment (arr is your array)...

require 'matrix'; p Matrix[*arr].map {|i| i.to_i}.to_a

...of course, just like Stefano's solution, the object must respond to
the #to_i method.

You can #join it and split it up (#each_slice) again (my first cool
solution, but looks _really_ ugly).  Mapping twice is the easiest and
is the way you probably should go.

Todd
This topic is locked and can not be replied to.