开发者

Ruby Array - highest integer

brand new to Ruby, and love it. Just playing around with the below code:

    public
    def highest 
      highest_number = 0
      each do |number|
        number = number.to_i
        highest_number = number if number > highest_number
        puts highest_number 
      end
    end


    array = %w{1 2 4 5 3 8 22 929 1000 2}
    array.highest

So at the moment the response I get is:

    1
    2
    4
    5
    5
    8
    22
    929
    1000
    1000

So it puts the array first, then the highest number from the array as well. However all I want it to is put the highest number only...

I have played around with this and can't figur开发者_如何学Pythone it out! Sorry for such a newbie question


The problem is that you have the puts statement inside the each loop, so during every iteration it prints out what the highest number currently is. Try moving it outside the each loop so that you have this:

public

def highest
  highest_number = 0
  each do |number| 
    number = number.to_i
    highest_number = number if number > highest_number
  end
  puts highest_number
end

array = %w{1 2 4 5 3 8 22 929 1000 2}
array.highest

Which produces the desired output:

1000


You could also save yourself some trouble by using max_by:

>> a = %w{1 2 4 5 3 8 22 929 1000 2}
=> ["1", "2", "4", "5", "3", "8", "22", "929", "1000", "2"]
>> m = a.max_by { |e| e.to_i }
=> "1000"

You could also use another version of max_by:

m = a.max_by(&:to_i)

to avoid the extra noise of the "block that just calls a method".

But this is probably a Ruby blocks learning exercise for you so using existing parts of the standard libraries doesn't count. OTOH, it is good to know what's in the standard libraries so punting to max_by or max would also count as a learning exercise.


You can do this instead and avoid the highest_number variable.

array = %w{1 2 4 5 3 8 22 929 1000 2}

class Array
  def highest
    collect { |x| x.to_i }. \
    sort.                   \
    last.to_i
  end
end

array.highest # 1000

The collect { |x| x.to_i } can also be written as collect(&:to_i) in this case.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜