0

你们 Ruby 专业人士会笑的,但我很难接受。我已经搜索和搜索并尝试了很多不同的东西,但似乎没有什么是正确的。我想我只是习惯于在 js 和 php 中处理数组。这是我想做的;考虑这个伪代码:

i = 0
foreach (items as item) {
  myarray[i]['title'] = item['title']
  myarray[i]['desc'] = item['desc']
  i++
}

对,所以我可以循环访问 myarray 或通过索引 (i) 访问“title”和“desc”。世界上最简单的事情。我找到了一些让它在 Ruby 中工作的方法,但它们都非常混乱或令人困惑。我想知道正确的方法,以及最干净的方法。

4

3 回答 3

0

我不太清楚你为什么要这样做,因为它似乎items已经是一个包含哈希的数组,并且在我下面的代码中,myarrayitems.

尝试使用each_with_index而不是foreach循环:

items.each_with_index do |item, index|
  myarray[index] = item
end

如果您在每个项目中都有额外的属性,例如 aid或某物,那么您需要在将项目添加到之前删除这些额外的属性myarray

于 2013-10-27T20:41:31.133 回答
0

除非您实际上正在更新my_array(这意味着可能有更好的方法来执行此操作),否则您可能需要 map 代替:

items = [
  {'title' => 't1', 'desc' => 'd1', 'other' => 'o1'},
  {'title' => 't2', 'desc' => 'd2', 'other' => 'o2'},
  {'title' => 't3', 'desc' => 'd3', 'other' => 'o3'},
]

my_array = items.map do |item|
  {'title' => item['title'], 'desc' => item['desc'] }
end

items    # => [{"title"=>"t1", "desc"=>"d1", "other"=>"o1"}, {"title"=>"t2", "desc"=>"d2", "other"=>"o2"}, {"title"=>"t3", "desc"=>"d3", "other"=>"o3"}]
my_array # => [{"title"=>"t1", "desc"=>"d1"}, {"title"=>"t2", "desc"=>"d2"}, {"title"=>"t3", "desc"=>"d3"}]
于 2013-10-27T21:02:28.127 回答
0
titles = ["t1", "t2", "t3"]
 descs = ["d1", "d2", "d3"]

h= Hash.new

titles.each.with_index{ |v,i| h[i] = {title: "#{v}" } }

puts h[0][:title] #=> t1
puts h            #=>  {0=>{:title=>"t1"}, 1=>{:title=>"t2"}...}

descs.each.with_index{ |v,i| h[i] = h[i].merge( {desc: "#{v}" } ) }

puts h[0][:desc] #=> d1
puts h           #=>  {0=>{:title=>"t1", :desc=>"d1"}, 1=>...
于 2013-10-27T21:06:24.330 回答