围绕嵌套数组

时间:2016-02-23 07:53:32

标签: arrays ruby

我有一个数组:

[["val1", ["The cat", "3"]], ["val2", ["Big", "Another", "6"]], ["val3", ["343"]]

通过使用以下代码修改我之前的问题here中的另一个数组:

array.group_by(&:first).map{|k, a| [k, a.map(&:last)]}

这个问题的答案可能会添加到上面的代码中,或者只是使用给定的数组。

我正在尝试将数组转换为:

[["val1", ["<a href='/guides/{#guide}/pages/the-cat'>The cat</a>", "<a href='/guides/{#guide}/pages/red-foo'>Red Foo</a>"]], ["val2", [""<a href='/guides/{#guide}/pages/big'>Big</a>", ""<a href='/guides/{#guide}/pages/another'>Another</a>", ""<a href='/guides/{#guide}/pages/6'>6</a>"]], ["val3", [""<a href='/guides/{#guide}/pages/joe'>Joe</a>"]]

链接围绕数组的数组值。

"<a href='/guides/{#guide}/pages/" + value_parameterized + "'>" + original_value + "</a>"
  • 它以一个字符串开头,该字符串构成a标记的开头。
  • 然后是复制值并在其上调用parameterize并将其放在第一个字符串之后的棘手部分。
  • 添加了另一个字符串。
  • 然后添加数组的原始字符串(或值)。
  • 最后添加a标记的结尾。

复制值并对其进行参数化然后将其传回正确的位置是我没有希望的地方。

最后,我将把嵌套数组转换为如下字符串:

["val1", "<a href='/guides/{#guide}/pages/the-cat'>The cat</a>, <a href='/guides/{#guide}/pages/red-foo'>Red Foo</a>"]

如果更容易修改或创建一个新数组,并且第二个值是一个字符串,那么我会非常高兴。

我不能使用Rails'link_to

1 个答案:

答案 0 :(得分:2)

Bruteforce方式是,

array = [["val1", ["The cat", "3"]], ["val2", ["Big", "Another", "6"]], ["val3", ["343"]]
array.each_with_object([]) do |val, out|
    result = [val.first]
    result << val.second.each_with_object([]) { |v, s_out| s_out << "<a href='/guides/{#guide}/pages/#{v.parameterize}'>#{v}</a>" } 
    out << result
end

# => [["val1", ["<a href='/guides/{#guide}/pages/the-cat'>The cat</a>", "<a href='/guides/{#guide}/pages/3'>3</a>"]], ["val2", ["<a href='/guides/{#guide}/pages/big'>Big</a>", "<a href='/guides/{#guide}/pages/another'>Another</a>", "<a href='/guides/{#guide}/pages/6'>6</a>"]], ["val3", ["<a href='/guides/{#guide}/pages/343'>343</a>"]]] 

一个班轮,

array.each_with_object([]) { |val, out| out << [val.first, val.second.each_with_object([]) { |v, s_out| s_out << "<a href='/guides/{#guide}/pages/#{v.parameterize}'>#{v}</a>" } ] }

Ruby#each_with_object,创建一个新数组。

要更改同一个数组,您可以使用Ruby#map!Ruby#collect!

array = [["val1", ["The cat", "3"]], ["val2", ["Big", "Another", "6"]], ["val3", ["343"]]]
array.collect! { |value| [value.first, value.second.collect! {|link| "<a href='/guides/{#guide}/pages/#{link.parameterize}'>#{link}</a>" } ] }

#=> [["val1", ["<a href='/guides/{#guide}/pages/the-cat'>The cat</a>", "<a href='/guides/{#guide}/pages/3'>3</a>"]], ["val2", ["<a href='/guides/{#guide}/pages/big'>Big</a>", "<a href='/guides/{#guide}/pages/another'>Another</a>", "<a href='/guides/{#guide}/pages/6'>6</a>"]], ["val3", ["<a href='/guides/{#guide}/pages/343'>343</a>"]]]

基准测试结果

                 user     system      total        real
each_with_object 0.000000   0.000000   0.000000 (  0.000610)
collect!         0.000000   0.000000   0.000000 (  0.000379)