我有一个哈希数组 @profiles,其中包含以下数据:
[{:user_id=>5, :full_name=>"Emily Spot"},{:user_id=>7, :full_name=>"Kevin Walls"}]
我想获取用户ID为7的全名。我正在尝试以下操作,但它抛出错误,表达式
@profiles.find{|h| h[':user_id'] == current_user.id}
为空。name = @profiles.find{ |h| h[':user_id'] == current_user.id }[':full_name']
如果我使用
select
而不是find
,那么会出现错误 - 没有将字符串隐式转换为整数。我该如何搜索哈希数组?
更新:
在@Eric的回答之后,我重构了我的工作模型和视图操作:
def full_names
profile_arr||= []
profile_arr = self.applications.pluck(:user_id)
@profiles = Profile.where(:user_id => profile_arr).select([:user_id, :first_name, :last_name]).map {|e| {user_id: e.user_id, full_name: e.full_name} }
@full_names = @profiles.each_with_object({}) do |profile, names|
names[profile[:user_id]] = profile[:full_name]
end
end
In the view....,
p @current_job.full_names[current_user.id]
@profiles.find { |hash| hash[:user_id] == 7 }
返回nil
,那么在没有安全导航符的情况下调用它的name
将会引发异常,而有了安全导航符,它只会返回nil
。 - Andrey Deinekonil&.non_existing_method
=>nil
- Andrey Deinekofull_name
,因为它没有实现该方法。 - Andrey Deineko