10

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

3 Answers 3

18

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

[1,2,3].join.to_i
0
14

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
3
  • Clever -- took me a minute to work out what's going on here. The value of the accumulator a after each element in the [1,2,3] is evaluated, respectively, is: 0*10+1 = 1; then 1*10+2 = 12; then 12*10+3 = 123. Dec 8, 2021 at 19:22
  • 1
    Welcome to all of you brought here by AoC 2021 day 8! :D Dec 10, 2021 at 7:42
  • Thanks, glad to be here! :-D Dec 10, 2021 at 15:24
7

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
1
  • Integer [0, 1, 1].join # => 9, you want Integer [0, 1, 1].join, 10 # => 11. Sep 9, 2011 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.