开发者

How to set fixed number of elements of array in Ruby

How to set fixed number of elements of an array in Ruby.

eg. a=["a","b","c","d"] Setting array size to 3 would output

a=["a","开发者_如何转开发b","cd"]


If you knew the elements were just one-character strings, you could do something like:

a.join.split '', 3

Otherwise:

a[0..1] + [a[2..-1].join]

Or perhaps:

a[0..1] << a[2..-1].join


class Array
  def squeeze(n, &p)
    p = Proc.new {|xs| xs.join} unless p
    arr = self[0..n-2]
    arr << p.call(self[n-1..-1])
  end
end

a = ['a', 'b', 'c', 'd', 'e']
a.squeeze(3) # => ["a", "b", "cde"]

It needs bounds checking but you get the idea. Note that the "combining" function can be given as a block argument:

[1, 2, 3, 4].squeeze(3) {|xs| xs.inject {|acc,x| acc+x}} # => [1, 2, 7]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜