Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

min_by Ruby (smallest value in associative array)

Tags:

ruby

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.

like image 417
chris Frisina Avatar asked Sep 22 '26 16:09

chris Frisina


1 Answers

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.

like image 57
Confusion Avatar answered Sep 27 '26 05:09

Confusion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!