How to avoid NoMethodError for missing elements in

2019-01-01 07:37发布

I'm looking for a good way to avoid checking for nil at each level in deeply nested hashes. For example:

name = params[:company][:owner][:name] if params[:company] && params[:company][:owner] && params[:company][:owner][:name]

This requires three checks, and makes for very ugly code. Any way to get around this?

16条回答
残风、尘缘若梦
2楼-- · 2019-01-01 08:14

I don't know if that's what you want, but maybe you could do this?

name = params[:company][:owner][:name] rescue nil
查看更多
心情的温度
3楼-- · 2019-01-01 08:14

Do:

params.fetch('company', {}).fetch('owner', {})['name']

Also at each step, you can use an appropriate method built in NilClass to escape from nil, if it were array, string, or numeric. Just add to_hash to the inventory of this list and use it.

class NilClass; def to_hash; {} end end
params['company'].to_hash['owner'].to_hash['name']
查看更多
牵手、夕阳
4楼-- · 2019-01-01 08:17

Write the ugliness once, then hide it

def check_all_present(hash, keys)
  current_hash = hash
  keys.each do |key|
    return false unless current_hash[key]
    current_hash = current_hash[key]
  end
  true
end
查看更多
孤独总比滥情好
5楼-- · 2019-01-01 08:21

Are you able to avoid using a multi-dimensional hash, and use

params[[:company, :owner, :name]]

or

params[[:company, :owner, :name]] if params.has_key?([:company, :owner, :name])

instead?

查看更多
登录 后发表回答