Ruby:条件会话的简写?

Hop*_*eam 1 ruby ruby-on-rails

1.是否有更简单的方法来编写这样的多个条件?

self.location = ""
self.location += geo["city"].to_s + ", " if geo["city"].present?
self.location += geo["regionName"].to_s + ", " if geo["regionName"].present?
self.location += geo["countryName"].to_s + ", " if geo["countryName"].present?
Run Code Online (Sandbox Code Playgroud)

2.还删除任何尾随逗号?

更新: 以下是我正在尝试使用Vee解决方案的确切代码

geo = JSON.parse(open('http://www.geoplugin.net/json.gp?ip=127.0.0.1').read)
fields_to_select = ["geoplugin_city", "geoplugin_regionName", "geoplugin_countryName"]
location = geo.select { |elem| fields_to_select.include? elem }.values.compact.join(', ')
Run Code Online (Sandbox Code Playgroud)

Ste*_*fan 7

这应该工作:

self.location = geo.values_at('city', 'regionName', 'countryName').compact.join(', ')
Run Code Online (Sandbox Code Playgroud)
  • values_at返回的值'city','regionName''countryName'(按该顺序)
  • compact删除nil
  • join 连接元素,将每个元素转换为字符串

由于您使用的是Rails,因此可以调用reject(&:blank?)而不是compact删除nil值,空值和空字符串.