Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Concatenate Integer Array to Single Integer in Ruby

Given the array [1,2,3], is there a method (other than just iteration) to convert it to the integer 123?

like image 740
KevDog Avatar asked Sep 09 '11 11:09

KevDog


3 Answers

Just join the array and convert the resulted string to an integer:

[1,2,3].join.to_i
like image 169
arnep Avatar answered Oct 20 '22 05:10

arnep


If you want to avoid converting to and from a String, you can use inject:

[1,2,3].inject{|a,i| a*10 + i}
#=> 123
like image 20
Mladen Jablanović Avatar answered Oct 20 '22 06:10

Mladen Jablanović


Personally I would use

Integer([1,2,3].join, 10) #=> 123

since it has the nice side-effect of throwing an exception that you can deal with if you have non-numeric array elements:

>> Integer([1,2,'a'].join, 10) # ArgumentError: invalid value for Integer: "12a"

Compare this to to_i:

>> [1,2,'a'].join.to_i #=> 12
like image 35
Michael Kohl Avatar answered Oct 20 '22 05:10

Michael Kohl