converting number to its digits as an array

I

Ian Ian

I'm new to ruby and I was trying to solve a problem where I convert a
number into an array in such a way.

If I have the number 12345, how do I take that number and put it into an
array but where each element is a digit of the number 12345?

If this is the wrong place to have posted such a question (for various
reasons) then let me know.
 
S

Steel Steel

Victor said:
I'm new to ruby and I was trying to solve a problem where I convert a
number into an array in such a way.

If I have the number 12345, how do I take that number and put it into an
array but where each element is a digit of the number 12345?

If this is the wrong place to have posted such a question (for various
reasons) then let me know.

irb(main):001:0> "12345".scan(/./)
=> ["1", "2", "3", "4", "5"]
 
J

Jörg W Mittag

Ian said:
I'm new to ruby and I was trying to solve a problem where I convert a
number into an array in such a way.

If I have the number 12345, how do I take that number and put it into an
array but where each element is a digit of the number 12345?

There's a myriad ways to do that. I find this one the simplest,
easiest to read and easiest to understand:

12345.to_s.chars.map(&:to_i)

jwm
 
V

Victor qwerty

If I try one of these methods, I still can't go from element to element
in the array. I don't want to just show a list, I want an actual array.
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

If I try one of these methods, I still can't go from element to element
in the array. I don't want to just show a list, I want an actual array.
All of these methods return an Array. Why don't you show us what you're
trying to do.
 
V

Victor qwerty

Josh said:
All of these methods return an Array. Why don't you show us what you're
trying to do.


It says I can't do the each method, but if I have the array, can't I
iterate through each element in the array?

x = 5 ** 500

x.to_s.scan(/./)

y = 0

x.each do |i|

i.to_i

y += i

end

puts y
 
B

Brian Candler

Victor said:
x = 5 ** 500

x.to_s.scan(/./)

The value of this expression is an array, but you don't assign it to
anything, so it is lost. Try:

digits = x.to_s.scan(/./)
y = 0

x.each do |i|

digits.each do |i|

That again does nothing - it converts i to an integer, but the resulting
value is discarded.

You probably meant:

val = i.to_i
y += val

or more simply,

y += i.to_i
 
V

Victor qwerty

Thank you so much! That really clarifies things. It did the program
successfully and now I know a little bit more about why.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,371
Latest member
Brkaa

Latest Threads

Top