在Ruby的填充的阵列的方法 [英] Method for padding an array in Ruby

查看:143
本文介绍了在Ruby的填充的阵列的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是我现在已经和它是有点工作:

Here's what I have now and it is somewhat working:

def padding(a, b, c=nil)
  until a[b-1]
    a << c
  end
end

这是当它的工作原理:

a=[1,2,3]
padding(a,10,"YES")
=>[1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]

a[1,2,3]
padding(a,10,1)
=>[1, 2, 3, 1, 1, 1, 1, 1, 1, 1]

但是,当我不为C

But it crashes when I do not enter a value for "c"

a=[1,2,3]
padding(a,10)
Killed

我应该如何追加是为了避免出车祸吗?
此外,你会如何建议更改此方法来使用它,如下所示:

How should I append this to avoid a crash? Additionally, how would you suggest changing this method to use it as follows:

[1,2,3].padding(10)
=>[1,2,3,nil,nil,nil,nil,nil,nil,nil]
[1,2,3].padding(10, "YES")
=>[1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]

我见过上的其他填充方法,但他们似乎并不如预期的作者是工作。所以,我决定放弃使我自己的一个镜头。感谢您的时间。

I've seen other padding methods on SO, but they don't seem to be working as intended by the authors. So, I decided to give making my own a shot. Thank you for your time.

编辑:谢谢大家的回答

推荐答案

你知道的 阵列#填充 方法: -

Do you know Array#fill method :-

它做什么你到底找。如果存在,为什么你想你自己的。

It does, what you exactly looking for. If it exist, why you want your own.

arup@linux-wzza:~> pry
[1] pry(main)> a=[1,2,3]
=> [1, 2, 3]
[2] pry(main)> a.fill('YES', 3...10)
=> [1, 2, 3, "YES", "YES", "YES", "YES", "YES", "YES", "YES"]
[3] pry(main)>

您可以的填写的阵列,任何你想要的方式。这是一个很酷的实现。试试看吧。

You can fill your array, whatever way you want. It is a cool implementation. Give it a try.

阅读它在你的控制台:

arup@linux-wzza:~> ri Array#fill

= Array#fill

(from ruby site)
------------------------------------------------------------------------------
  ary.fill(obj)                                 -> ary
  ary.fill(obj, start [, length])               -> ary
  ary.fill(obj, range )                         -> ary
  ary.fill { |index| block }                    -> ary
  ary.fill(start [, length] ) { |index| block } -> ary
  ary.fill(range) { |index| block }             -> ary

------------------------------------------------------------------------------

The first three forms set the selected elements of self (which may be the
entire array) to obj.

A start of nil is equivalent to zero.

A length of nil is equivalent to the length of the array.

The last three forms fill the array with the value of the given block, which
is passed the absolute index of each element to be filled.

Negative values of start count from the end of the array, where -1 is the last
element.

  a = [ "a", "b", "c", "d" ]
  a.fill("x")              #=> ["x", "x", "x", "x"]
  a.fill("z", 2, 2)        #=> ["x", "x", "z", "z"]
  a.fill("y", 0..1)        #=> ["y", "y", "z", "z"]
  a.fill { |i| i*i }       #=> [0, 1, 4, 9]
  a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]

这篇关于在Ruby的填充的阵列的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆