假设我有以下哈希数组:
h = [{"name" => "bob"}, {"car" => "toyota"}, {"age" => "25"}]
我有以下要匹配的键:
k = 'car'
如何将“k”匹配到“h”并在匹配后删除每个元素以使其返回:
h = [{"name" => "bob"}, {"car" => "toyota"}]
假设我有以下哈希数组:
h = [{"name" => "bob"}, {"car" => "toyota"}, {"age" => "25"}]
我有以下要匹配的键:
k = 'car'
如何将“k”匹配到“h”并在匹配后删除每个元素以使其返回:
h = [{"name" => "bob"}, {"car" => "toyota"}]
只需将哈希转换为数组,完成您的任务,然后再转换回来
h = {"name" => "bob", "car" => "toyota", "age" => "25"}
array = h.to_a.flatten
index = array.index('car') + 1
h = Hash[*array[0..index]]
=> {"name"=>"bob", "car"=>"toyota"}
顺便说一下,哈希是从 Ruby 1.9 开始排序的
ar = [{"name" => "bob"}, {"car" => "toyota"}, {"age" => "25"}]
p ar[0 .. ar.index{|h| h.key?('car')}] #=>[{"name"=>"bob"}, {"car"=>"toyota"}]
我喜欢 megas 的版本,因为它短小精悍。另一种更明确的方法是遍历每个散列的键数组。散列的键保存在有序数组(http://ruby-doc.org/core-1.9.3/Hash.html)中。它们按首次进入时的顺序排列。因此,您可以尝试以下操作:
newArray = Array.new
h.each do |hash| # Iterate through your array of hashes
newArray << hash
if hash.has_key?("car") # check if this hash is the "car" hash.
break # exits the block
end
end
当然,这一切都取决于数组是否以正确的顺序创建。如果是,那你就是金子。
根据定义,哈希是无序集,因此您请求的内容有些不确定。但是,您可以执行类似 hack 的操作:
h = {"name" => "bob", "car" => "toyota", "age" => "25"}
matched = false
key_given = "car"
h.each do |k,v|
if matched
h.delete(k)
end
if k == key_given
matched = true
next
end
end
我在这里参加聚会已经很晚了。我一直在寻找解决同样问题的方法,但我不喜欢这些答案。所以,这是我的方法:
class Array
def take_until(&blk)
i = find_index &blk
take(i + 1)
end
end
h = [{"name" => "bob"}, {"car" => "toyota"}, {"age" => "25"}]
k = 'car'
h.take_until { |x| x.has_key?(k) }
=> [{"name"=>"bob"}, {"car"=>"toyota"}]