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)
这应该工作:
self.location = geo.values_at('city', 'regionName', 'countryName').compact.join(', ')
Run Code Online (Sandbox Code Playgroud)
由于您使用的是Rails,因此可以调用reject(&:blank?)而不是compact删除nil值,空值和空字符串.
| 归档时间: |
|
| 查看次数: |
111 次 |
| 最近记录: |