【问题标题】:If a key has a value then print the value ruby如果键有值,则打印值 ruby
【发布时间】:2018-05-16 02:40:53
【问题描述】:

我试图仅在键 escalation_policies 具有值时才设置键 self 的值。这是一个没有升级策略的计划示例,因此我不想要键 self

的值
{"schedules"=>
  [{"id"=>"0000000",
    "type"=>"schedule",
    "summary"=>"-PROD-",
    "self"=>"https://api.pagerduty.com/schedules/",
    "html_url"=>"https://pagerduty.com/schedules/",
    "name"=>"-PROD-",
    "time_zone"=>"America/",
    "description"=>nil,
    "privilege"=>nil,
    "users"=>
     [{"id"=>"0000000",
       "type"=>"user_reference",
       "summary"=>"DOo Kkkk",
       "self"=>"https://api.pagerduty.com/users/",
       "html_url"=>"https://target.pagerduty.com/users/"}],
    "escalation_policies"=>[],
    "teams"=>[]},
}

我克服这一挑战的代码是:

somefile = File.open("Schedule_Api.txt", "a+")
  jdoc.fetch("schedules").each do |schedule|
    somefile.puts schedule["self"] if schedule["escalation_policies"].exists? == true 
  end
somefile.close

这个变量jdoc 是网站的卷曲。这就是我从中得到的结果是undefined methodexists?对于 []:Array (NoMethodError). Is there another alternative to this then the methodexists?`。任何帮助都会有所帮助!谢谢!

【问题讨论】:

  • 我建议改写“仅当密钥 escalation_policies 具有值时”。尽管在更高的非技术层面上,空数组表示没有值,但这可能会让其他人感到困惑,就像对我一样。最好说“仅当键 escalation_policies 的哈希值是一个不为空的数组时”(或者其大小 > 0)。
  • 会的!谢谢!

标签: json ruby hash key


【解决方案1】:

.exists? 是来自 ActiveRecord 的方法,而不是在 Array 上。

如果你想测试空数组,你可能想这样做

somefile.puts schedule["self"] unless schedule["escalation_policies"].empty?

如果您想测试任何值,只需执行

somefile.puts schedule["self"] if schedule["escalation_policies"]

应该工作

【讨论】:

  • 太棒了!你是对的!我明白为什么我的代码不正确,但我很高兴至少我很接近!再次感谢您!
【解决方案2】:

试试:

  if schedule.has_key?("escalation_policies")

你也可以测试:

  if schedule["escalation_policies"]

不仅在key不存在时返回false,如果key存在时返回false,对应的值为nil。

如果值的缺失总是由空数组 ([]) 表示,那么您可以使用 Rick Sullivan 在他的回答中提到的 schedule["escalation_policies"].empty?schedule["escalation_policies"].any? 来测试数组大小 > 0.

【讨论】:

  • 谢谢!你说的也对,看来我还有很多东西要学。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 1970-01-01
  • 2020-04-09
相关资源
最近更新 更多