如何在Ruby中设置固定数量的数组元素

时间:2021-09-04 09:12:22

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

如何在Ruby中设置固定数量的元素。

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

例如。 a = [“a”,“b”,“c”,“d”]输出数组大小为3

a=["a","b","cd"]

2 个解决方案

#1


3  

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]

#2


6  

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

#1


3  

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]

#2


6  

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