Sebastian Hungerecker
7/31/2008 10:24:00 AM
Web Reservoir wrote:
> Now when you type RUBY you should get the total as 9+3+2+7 = (21) 2+1 =
> 3
> where R = 9, U = 3, B = 2 and y = 7 ( as shown above )
> ...
> I would like to code this in Ruby. Pl. help me with this code.
>> "RUBY".unpack("C*")
=> [82, 85, 66, 89]
( unpack("C*") gives you the ASCII value of each character in the string)
>> ?A
=> 65
(The ASCII value of A is 65)
>> "RUBY".unpack("C*").map {|x| x - ?A}
=> [17, 20, 1, 24]
>> "RUBY".unpack("C*").map {|x| (x-65)%9}
=> [8, 2, 1, 6]
>> "RUBY".unpack("C*").map {|x| (x-65)%9 + 1}
=> [9, 3, 2, 7]
>> "RUBY".unpack("C*").inject(0) {|s,x| s + (x-65)%9 + 1}
=> 21
>> "RUBY".unpack("C*").inject(0) {|s,x| s + (x-65)%9 + 1}.to_s.split(//)
=> ["2", "1"]
>> "RUBY".unpack("C*").inject(0) {|s,x| s + (x-65)%9 +
1}.to_s.split(//).inject(0) {|s,x| s + x.to_i}
=> 3
HTH,
Sebastian
--
NP: Skillet - The Last Night
Jabber: sepp2k@jabber.org
ICQ: 205544826