The maximum value in the array of objects

I'm new to ruby. I am trying to do the following but failed.

I have an array of objects, let's call it objs. Each object has several properties, one of which is a variable that contains a number, let it val1. I want to iterate over an array of objects and determine the maximum value of val1 through all objects.

I tried the following:

def init(objs)
  @objs = objs
  @max = 0
  cal_max
end

def cal_max

  @max = @objs.find { |obj| obj.val1 >= max }

  # also tried
  @objs.each { |obj| @max = obj.val1 if obj.val1 >= @max }

end

As I said, I'm just learning blocks.

Any suggestion is welcome.

thank

+4
source share
2 answers

Say you created the following model:

class SomeObject
  attr_accessor :prop1, :prop2, :val1

  def initialize(prop1, prop2, val1)
    @prop1 = prop1
    @prop2 = prop2
    @val1  = val1
  end
end

#define your objects from the class above
david  = SomeObject.new('David',  'Peters', 23)
steven = SomeObject.new('Steven', 'Peters', 26)
john   = SomeObject.new('John',   'Peters', 33)

#define an array of the above objects
array = [david, steven, john]

max_by, , val1. val1, .

array.max_by {|e| e.val1 }.val1 #=> 33

( ), :

david  = {f_name: 'David',  s_name: 'Peters', age: 23}
steven = {f_name: 'Steven', s_name: 'Peters', age: 26}
john   = {f_name: 'John',   s_name: 'Peters', age: 33}

array = [david, steven, john]
array.max_by { |hash| hash[:age] }[:age] #=> 33
+3
@objs.map(&:val1).max

, . :

@objs.map{ |o| o.val1 }.max

, ( Cary Swoveland ):

@objs.max_by(&:val1).val1
+3

Source: https://habr.com/ru/post/1654880/


All Articles