From: Robert Dober Date: 2010-03-09T16:50:15+09:00 Subject: Re: Shortest code On Mon, Mar 8, 2010 at 10:38 PM, Prasanth Ravi wrote: > Robert Dober wrote: >> On Mon, Mar 8, 2010 at 10:10 PM, Prasanth Ravi >> wrote: >>> hi i'm a newbie in ruby and was test out some interesting problems in >>> ruby, >>> >>> i came across a small one to print the sum of positive numbers from a >>> list of n numbers... with the shortest code possible.. >>> >>> well the best i could do was, >>> puts gets.split(' ').inject(0){|sum,x| x.to_i>0?sum+x.to_i : sum} >> I am afraid so >> puts gets.split.map(&:to_i).inject(&:+) >> although in Ruby 1.8 you need >> gets.split.inject(0){ |sum, x | sum + x.to_i } >> or >>    ... inject{ | sum, x | sum.to_i + x.to_i } >> if you prefer. >> >> What do *you* think is the most readable solution BTW ;)? >> >> Cheers >> Robert >> >> P.S. >> BTW if you meant to not use negative numbers (sorry my English is very >> basic) >> >> map(&:to_i).select{ |x| x > 0 }. ... >> >> would be my choice. >> >> R. > > tx for the reply, i originally used > y=0 > gets.split.each{ |x| >  z=x.to_i >  y+=z if z>0 > } > print y > > --46 chars > > puts gets.split.map(&:to_i).select{|x| x>0}.inject(&:+) > > --53 chars > I feel that your code has less characters and mine is shorter :) R.