Forum: Ruby (mandriva,eclipse) extract digits from fixnums

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.
Olivier L. (Guest)
on 2009-04-30 15:55
(Received via mailing list)
hi,

I want to do a basic thing but without succes:
if a=1232, let nb_nb=4 (the number of digits)
for i from 1 to nb_nb, I want the following results:
i=1 => res=1 (first digit of a) and NOT the number 01 (with a zero in
front of the 1)
i=2 => res=2 (same thing)
i=3 => res=3
i=4 => res=2

I tried a few things, like convert the number in array (it seems to keep
the "0" in the result)...

do you have a solution?

olivier.






___________________________________________________________________________
Yahoo! Mail réinvente le mail ! Découvrez le nouveau Yahoo! Mail et son
interface révolutionnaire.
http://fr.mail.yahoo.com
Robert S. (Guest)
on 2009-04-30 16:38
(Received via mailing list)
You could try

a.to_s.split(//).collect {|s| s.to_i}

and extract nb_nb elements.

Bob Schaaf
7stud -. (Guest)
on 2009-04-30 16:58
Olivier L. wrote:
> hi,
>
> I want to do a basic thing but without succes:
> if a=1232, let nb_nb=4 (the number of digits)
> for i from 1 to nb_nb, I want the following results:
> i=1 => res=1 (first digit of a) and NOT the number 01 (with a zero in
> front of the 1)
> i=2 => res=2 (same thing)
> i=3 => res=3
> i=4 => res=2
>
> I tried a few things, like convert the number in array (it seems to keep
> the "0" in the result)...
>
> do you have a solution?
>

It's not clear to me what you want to do, but maybe this will help:

a=1232
str = a.to_s
p str

--output:--
"1232"

digits = []
str.length.times do |i|
  digits << str[i, 1]
end

p digits

--output:--
["1", "2", "3", "2"]

> res=1 (first digit of a) and NOT the number 01

1 and 01 are the same *number*.
This topic is locked and can not be replied to.