简体   繁体   English

在红宝石数组内打印哈希?

[英]print hash within array in ruby?

if I have an array with hashes inside, how do I print only the hash keyvalue pairs ? 如果我有一个带有散列的数组,如何仅打印散列键值对?

  complex_array= [ 1,2, 3, "string", 
               {"app1"=>"123 happy street",
                "app2"=>"daf 3 street", 
                "app3"=>"random street"}, "random", {"another"=>"hash"}
               ]

I'm trying to do: 我正在尝试做:

complex_array.select{|x|
 puts x["app1"];
 }

that doesn't work, because with arrays you need an index parameter (no conversion of string to integer error) 那是行不通的,因为使用数组需要索引参数(不将字符串转换为整数错误)

So how do I only print the values of the hash(s) without specifying the index of the hash within the array first, or is that the only way ? 那么,如何只显示哈希值而不先指定数组中哈希的索引,还是唯一的方法?

You can loop through each element of the array and determine if that class of the element is a hash. 您可以遍历数组的每个元素,并确定该元素的类是否为哈希。 If so, then puts the key value pairs of that hash element. 如果是这样,则放置该哈希元素的键值对。 The second looping is necessary in case there are multiple key value pairs. 如果有多个键值对,则必须进行第二次循环。

 complex_array.each do |element|
   if element.class == Hash
     element.each do |key, value|
       puts "key: #{key}, value: #{value}"
     end
   end
 end

Just select the elements that are hashes, then for each hash, print the key-value pairs: 只需选择散列元素,然后为每个散列打印键值对:

complex_array.select { |e| e.is_a? Hash }
             .each { |h| h.each { |k,v| puts "#{k}=>#{v}" } }
  # app1=>123 happy street
  # app2=>daf 3 street
  # app3=>random street
  # another=>hash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM