Convert elements of array into a single integer

Hi,

I've tried searching for this on the forum and couldn't find an answer.
Apologies if it's already out there.

I've converted the digits of an integer into elements of an array, like
so:

x = some_integer

y = "#{x}".scan(/./)

Now, after using y for my nefarious purposes, I would like to re-convert
the elements (still containing one digit each) into an integer.

I don't mind writing a routine for it, but was wondering if there's some
magical way to do it quicker :slight_smile:

Ta,

Anna

路路路

--
Posted via http://www.ruby-forum.com/.

Hi,

I've tried searching for this on the forum and couldn't find an answer.
Apologies if it's already out there.

I've converted the digits of an integer into elements of an array, like
so:

x = some_integer

y = "#{x}".scan(/./)

Better

y = x.to_s.scan /./

You can also do this numerically

irb(main):008:0> x = 113453
=> 113453
irb(main):009:0> y =
=>
irb(main):010:0> while x > 0; x, b = x.divmod 10; y.unshift b; end
=> nil
irb(main):011:0> y
=> [1, 1, 3, 4, 5, 3]

respectively

irb(main):015:0> x = 113453
=> 113453
irb(main):016:0> y =
=>
irb(main):017:0> while x > 0; x, b = x.divmod 10; y.unshift b.to_s; end
=> nil
irb(main):018:0> y
=> ["1", "1", "3", "4", "5", "3"]

or even

irb(main):030:0> x = 113453
=> 113453
irb(main):031:0> y =
=>
irb(main):032:0> while x > 0; y.unshift((x, b = x.divmod 10).last.to_s); end
=> nil
irb(main):033:0> y
=> ["1", "1", "3", "4", "5", "3"]

Now, after using y for my nefarious purposes, I would like to re-convert
the elements (still containing one digit each) into an integer.

You make me curious...

I don't mind writing a routine for it, but was wondering if there's some
magical way to do it quicker :slight_smile:

No magic needed

z = y.join.to_i

Kind regards

robert

路路路

On Thu, Oct 11, 2012 at 8:14 PM, Anna Baas <lists@ruby-forum.com> wrote:

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

Assuming y is an array like ['1', '2', '3']:

# join the array into a string like "123" and convert to an integer:
x = y.join('').to_i

The other way around can be done similarly:
y = x.to_s.split('') # convert integer to string and split between characters

-- Matma Rex

路路路

2012/10/11 Anna Baas <lists@ruby-forum.com>:

x = some_integer
y = "#{x}".scan(/./)

Thank you both!

路路路

--
Posted via http://www.ruby-forum.com/.