chris Frisina
chris Frisina

Reputation: 19688

min_by Ruby (smallest value in associative array)

I have the following in a model class User:

  def thisUsersUserRole
    userRoles = []
    self.userRoles.each do |ur|
      userRoles << { "id" => ur.role_id, "name" => ur.roleName }
    end
    #line in question
    userRoles.values.min_by(&:first)
    # puts userRoles
  end

The puts shows the following:

{"id"=>1, "name"=>"admin"}
{"id"=>2, "name"=>"owner"}
{"id"=>3, "name"=>"manager"}

I am trying to search the array (no more than 10 total, but from my research this is the least expensive method) and return the "name" attribute value of the lowest "id" value in the hash/associative array.

How do I use the min_by to accomplish this. The documentation isn't making any sense... Please help me understand the syntax as well, as just providing me the correct line won't help me learn.

Upvotes: 2

Views: 4968

Answers (2)

Confusion
Confusion

Reputation: 16841

Given the existing code and your response to my comment, I think this is what you want:

role_hash_with_smallest_id = userRoles.min_by {|role_hash| role_hash['id']}
role_hash_with_smallest_id['name']

However, there is probably a much simpler way:

role_with_smallest_id = self.userRoles.min_by {|role| role.id}
role_with_smallest_id.name

which can be abbreviated as

role_with_smallest_id = self.userRoles.min_by(&:id)
role_with_smallest_id.name

This is assuming self.userRoles already is an Enumerable.

Upvotes: 6

xdazz
xdazz

Reputation: 160833

Try below:

def thisUsersUserRole
  userRoles.min_by(&:role_id).roleName
end

Edit: If userRoles is an array of hash, then try:

def thisUsersUserRole
  userRoles.min_by{ |ur| ur['id'] }['roleName']
end

Upvotes: 3

Related Questions