按3个组连接数组元素?

时间:2014-02-22 20:05:01

标签: ruby

我有这个数组:

strings = %w(John likes Pie Diana prefers Cupcakes)

看起来像:

strings[0] -> "John"
strings[1] -> "likes"
strings[2] -> "Pie"
strings[3] -> "Diana"
strings[4] -> "prefers"
strings[5] -> "Cupcakes"

我怎样才能把它变成这个?

strings[0] -> "John likes Pie"
strings[1] -> "Diana prefers Cupcakes"

2 个答案:

答案 0 :(得分:12)

strings = strings.each_slice(3).map{|a| a.join(" ")}

答案 1 :(得分:0)

它出现(注意突出显示)动词是小写的,其他一切都是大写的。假设是*的情况,并且主语('John')和动词('likes')始终是单个单词,并且只有对象的第一个单词('Apple pie')大写,这应该有效:

def pull_substrings(strings)
  (strings.each_with_index
          .select { |w,_| w[0] =~ /[a-z]/ }
          .map { |_,i| i-1 } << strings.size)
          .each_cons(2).map { |f,lp1| strings[f...lp1].join(' ') }
end

我们试一试:

strings = %w[John likes Hot Dogs Diana prefers Cupcakes ] +
          %w[Billy-Bob devourers Hot Dogs Chips And Beer]
  #=> ["John", "likes", "Hot", "Dogs",
  #    "Diana", "prefers", "Cupcakes",
  #    "Billy-Bob", "devourers", "Hot", "Dogs", "Chips", "And", "Beer"]

pull_substrings(strings)
  #=> ["John likes Hot Dogs", "Diana prefers Cupcakes",
  #    "Billy-Bob devourers Hot Dogs Chips And Beer"]

以上是数组strings

的内容
# Save each word with its index
a = strings.each_with_index
  #=> #<Enumerator: ...>
  a.to_a #=> [["John", 0], ["likes", 1], ["Hot", 2], ["Dogs", 3],
         #    ["Diana", 4], ["prefers", 5], ["Cupcakes", 6],
         #    ["Billy-Bob", 7], ["devourers", 8], ["Hot", 9], ["Dogs", 10],
         #      ["Chips", 11], ["And", 12], ["Beer", 13]]

# Locate the positions of the verbs    
b = a.select { |w,_| w[0] =~ /[a-z]/ }
  #=> [["likes", 1], ["prefers", 5], ["devourers", 8]]

# Convert to the locations of the subjects (offsets where strings begin)    
c = b.map { |_,i| i-1 }
  #=> [0, 4, 7]

# Add the position of the last word of the last substring plus 1    
d = c << strings.size
  #=> [0, 4, 7, 14]

# Look at each pair of subject offsets      
e = (d).each_cons(2)
  #=> #<Enumerator: ...>
  e.to_a #=> [[0, 4], [4, 7], [7, 14]]

# Map each pair of offsets to a substring       
e.map { |f,lp1| strings[f...lp1].join(' ') }
  #=> ["John likes Hot Dogs",
  #    "Diana prefers Cupcakes",
  #    "Billy-Bob devourers Hot Dogs Chips And Beer"]

传递到e后面的块的map的第一个元素是`[0, 4], so f =&gt; 0,lp1 =&gt; 4`和

strings[0...4].join(' ') => ["John", "likes", "Hot", "Dogs"] => "John likes Hot Dogs"

我最初尝试将strings转换为字符串,用空格分隔的单词,并尝试使用正则表达式,但这是有问题的。

  • 双关语意外