【问题标题】:Ruby: How can I make these objects the same?Ruby:我怎样才能使这些对象相同?
【发布时间】:2011-01-29 14:38:23
【问题描述】:

所以我有以下哈希/数组:

{"number"=>[{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}, {"tracking"=>"9102901001301227214058"}]}

{"number"=>{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}}

第一个哈希有一个number 的数组,而第二个没有。

试图循环遍历数据会造成严重破坏(特别是当只有一个跟踪/注释组合时)。

最终我希望能够在每个跟踪/注释组合上执行 each 循环。

【问题讨论】:

    标签: ruby arrays hash each


    【解决方案1】:
    h1={"number"=>[{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}, {"tracking"=>"9102901001301227214058"}]}
    h2={"number"=>{"tracking"=>"1Z81E74W0393736553", "notes"=>"Example note"}}
    [h1["number"]].flatten
      => [{"notes"=>"Example note", "tracking"=>"1Z81E74W0393736553"}, {"tracking"=>"9102901001301227214058"}]
    [h2["number"]].flatten
      => [{"notes"=>"Example note", "tracking"=>"1Z81E74W0393736553"}]
    

    现在,每个都是哈希数组,您可以使用 each 来遍历它们。

    【讨论】:

      【解决方案2】:

      这样的?

      hash["number"] = [ hash["number"] ] unless hash["number"].kind_of?(Array)
      

      【讨论】:

        猜你喜欢
        • 2022-10-04
        • 2018-03-26
        • 1970-01-01
        • 2016-08-28
        • 1970-01-01
        • 2020-02-29
        • 2021-09-17
        • 2017-06-02
        • 2014-12-16
        相关资源
        最近更新 更多