更容易编写的方法如果hash包含 - Ruby

Lui*_*igi 0 ruby hash model ruby-on-rails

我在我的模型的初始化方法中有以下内容:

@home_phone = contact_hash.fetch('HomePhone')
Run Code Online (Sandbox Code Playgroud)

但是,有时候我需要这个:

@home_phone = contact_hash.fetch('number')
Run Code Online (Sandbox Code Playgroud)

此外,有时这些都不是真的,我将需要该home_phone属性为空.

如何在不创建如此大循环的情况下编写出来:

if contact_hash.has_key?('HomePhone')
  @home_phone = contact_hash.fetch('HomePhone')
elsif contact_hash.has_key?('number')
  @home_phone = contact_hash.fetch('number')
else 
  @home_phone = ""
end
Run Code Online (Sandbox Code Playgroud)

knu*_*nut 7

你可以试试

@home_phone = contact_hash.fetch('HomePhone', contact_hash.fetch('number', ""))
Run Code Online (Sandbox Code Playgroud)

或更好

@home_phone = contact_hash['HomePhone'] || contact_hash['number'] ||  ""
Run Code Online (Sandbox Code Playgroud)