0

我有一个看起来像这样的数组:

array = [
  "timestamp 1",
  "data 1",
  "data 2",
  "data 3",
  "timestamp 2",
  "data "1",
  "timestamp 3",
  ".." 
]
  etc

我想遍历我的数组,并将其转换为如下所示的哈希数据结构:

hash = { 
  "timestamp 1" => [ "data 1", " data 2", "data 3" ],
  "timestamp 2" => [ "data 1" ],
}

我想不出一个好的“红宝石”方式来做这件事。我正在遍历数组,我似乎无法弄清楚如何跟踪我所在的位置,并根据需要分配给哈希。

# Let's comb through the array, and map the time value to the subsequent lines beneath
array.each do |e|
  if timestamp?(e)
    hash["#{e}"] == nil
  else
    # last time stamp here => e
end

编辑:这是时间戳?方法

def timestamp?(string)
  begin
    return true if string =~ /[a-zA-z][a-z][a-z]\s[a-zA-z][a-z][a-z]\s\d\d\s\d\d:\d\d:\d\d\s\d\d\d\d/
    false
  rescue => msg
    puts "Error in timestamp? => #{msg}"
    exit
  end
end
4

7 回答 7

2

我会做如下:

array = [
  "timestamp 1",
  "data 1",
  "data 2",
  "data 3",
  "timestamp 2",
  "data 1", 
]

Hash[array.slice_before{|i| i.include? 'timestamp'}.map{|a| [a.first,a[1..-1]]}]
# => {"timestamp 1"=>["data 1", "data 2", "data 3"], "timestamp 2"=>["data 1"]}
于 2013-07-29T15:03:14.870 回答
2
array = [
  "timestamp 1",
  "data 1",
  "data 2",
  "data 3",
  "timestamp 2",
  "data 1",
  "timestamp 3",
  "data 2" 
]

hsh = {}
ary = []

array.each do |line|
  if line.start_with?("timestamp")
    ary = Array.new
    hsh[line] = ary
  else 
    ary << line
  end
end

puts hsh.inspect
于 2013-07-29T15:09:31.117 回答
1
Hash[array.slice_before{|e| e.start_with?("timestamp ")}.map{|k, *v| [k, v]}]

输出

{
  "timestamp 1" => [
    "data 1",
    "data 2",
    "data 3"
  ],
  "timestamp 2" => ["data 1"],
  "timestamp 3" => [".."]
}
于 2013-07-29T15:05:28.110 回答
0

您可以使用外部变量跟踪最后一个哈希键。它将在所有迭代中持续存在:

h = {}
last_group = nil
array.each do |e|
  if timestamp?(e)
    array[e] = []
    last_group = e
  else
    h[last_group] << e
  end
end
于 2013-07-29T15:03:15.560 回答
0
last_timestamp = nil
array.reduce(Hash.new(){|hsh,k| hsh[k]=[]}) do |hsh, m|
  if m =~ /timestamp/
    last_timestamp = m
  else
    hsh[last_timestamp] << m
  end
  hsh
end
于 2013-07-29T15:05:03.503 回答
0
hash = (Hash.new { |this, key| this[key] = [] } ).tap do |hash|
  current_timestamp = nil
  array.each do |element|
    current_timestamp = element if timestamp? element
    hash[current_timestamp] << element unless timestamp? element
  end
end

使用外部变量来跟踪当前时间戳,但将其包装在闭包中以避免污染命名空间。

于 2013-07-29T15:53:20.590 回答
0

我知道这已经得到了回答,但是有很多方法可以做到这一点。

我更喜欢这两种方式,它们可能不快,但我发现它们可读:

my_hash = Hash.new
array.slice_before(/timestamp/).each do |array|
  key, *values = array
  my_hash[key] = values
end

或者

one_liner = Hash[array.slice_before(/timestamp/).map{|x|[x.shift, x]}]
于 2013-07-30T07:28:25.603 回答