Robert Dober wrote: > On Mon, Mar 8, 2010 at 10:10 PM, Prasanth Ravi <dare.take / gmail.com> > 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 seems going the old fashioned way is shorter code, yup wanted for x>0 and between this was a problem to see on different languages python was around 26 , so i was thinking if i could do less than that on ruby... -- Posted via http://www.ruby-forum.com/.