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.


>
> is there a shorter version?
> --
> Posted via http://www.ruby-forum.com/.
>
>



-- 
Learning without thought is labor lost; thought without learning is perilous.--- Confucius