From: Adam Shelly Date: 2008-08-01T03:15:01+09:00 Subject: Re: Help me with this Numerology code please... On 7/31/08, Dave Bass wrote: > Karl-Heinz Wild wrote: > > On 31.07.2008, at 12:23, Sebastian Hungerecker wrote: > > > >> 1}.to_s.split(//).inject(0) {|s,x| s + x.to_i} > >> => 3 > > > > > > "RUBY".unpack("C*").inject(0) { |s,x| s + (x-64)%9 }%9 > > => 3 > > > > whouldn't that be better? > > Obviously the harder to understand, the better. There's also the small issue it gives inconsistent results. irb(main):022:0> Name='I' => "I" irb(main):023:0> Name.unpack("C*").inject(0) {|s,x| s + (x-65)%9 + irb(main):024:1* 1}.to_s.split(//).inject(0) {|s,x| s + x.to_i} => 9 irb(main):025:0> Name.unpack("C*").inject(0) { |s,x| s + (x-64)%9 }%9 => 0 And neither of these handle the case where you have to go through more than two reductions. The OP seems to be just learning ruby, so let's make this a learning exercise by turning the manual process directly into code. -Adam ---------------Numberology.rb------------------------------------ # first make a table to hold the number for every letter number_of = {} i = 1 #starting with 1... ('A'..'Z').each {|letter| #go through all the letters... number_of[letter] = i #and assign a number i+=1 #increase the number for the next letter i=1 if i>9 #go back to 1 after 9 } i=0 #do the same thing for .... ('0'..'9').each{|digit| #the text representation of each number number_of[digit] = i i+=1 } namenumber=0 #make a variable to store the namenumber puts "enter a name" #ask for... name = gets().chomp #and get a name (chomp off the newline char) name.upcase! #convert it to uppercase to match the table letters = name.split('') #split it into an array of individual letters #convert to numbers: numbers = letters.map{ |letter| #'map' each letter to its number number_of[letter] #using the table we made } #now we have an array of numbers #we may have to do the next part more than once, so start a loop loop do sum = 0 #start with 0 numbers.each{ |number| #for each number in the array... sum+= number #add it to the sum } if sum <=9 #if the sum is one digit... namenumber = sum # it is our final number break # so break out of the loop else #otherwise digits = sum.to_s.split('') # split the number into single digits numbers = digits.map{|digit| # map each text digit number_of[digit] #to it's actual number, } #updating the array of numbers end end #end of loop, go back to loop start puts "The number of #{name} is #{namenumber}" #show result