On Mon, Mar 8, 2010 at 10:38 PM, Prasanth Ravi <dare.take / gmail.com> wrote:
> 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
>> =A0 =A0... 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=3D0
> gets.split.each{ |x|
> =A0z=3Dx.to_i
> =A0y+=3Dz 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.