2

私はモデルクラスに次のものを持っています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

putsは次のことを示しています。

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

私は配列を検索しようとしています (合計で 10 以下ですが、私の調査ではこれが最も安価な方法です) 、ハッシュ/連想配列"name"の最小値の属性値を返します。"id"

min_byを使用してこれを達成するにはどうすればよいですか。ドキュメンテーションは意味がありません...正しい行を提供するだけでは学習に役立たないため、構文も理解できるようにしてください。

4

2 に答える 2

5

既存のコードと私のコメントに対するあなたの応答を考えると、これがあなたが望むものだと思います:

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

ただし、おそらくもっと簡単な方法があります。

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

これは次のように省略できます

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

これは、self.userRolesすでにEnumerable.

于 2012-12-25T12:24:44.627 に答える
3

以下を試してください:

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

編集:userRolesハッシュの配列の場合は、次を試してください:

def thisUsersUserRole
  userRoles.min_by{ |ur| ur['id'] }['roleName']
end
于 2012-12-25T11:30:49.067 に答える