2011-05-22 35 views

回答

301

如何使用unshift方法?

ary.unshift(obj, ...) → ary
Prepends objects to the front of self, moving other elements upwards.

而且在使用中:

irb>> a = [ 0, 1, 2] 
=> [0, 1, 2] 
irb>> a.unshift('x') 
=> ["x", 0, 1, 2] 
irb>> a.inspect 
=> "["x", 0, 1, 2]" 
+0

這是我一直在尋找的那個,忘了名字。 – 2011-05-22 01:50:54

+0

@Ed:這就是爲什麼你的書籤http://www.ruby-doc.org/。 「shift」和「unshift」在數組的開始處運行,結尾處爲「push」和「pop」。 – 2011-05-22 01:52:45

+1

我看了看,只是沒有看到他們在一個快速掃描。 – 2011-05-22 06:25:17

38

您可以使用insert

a = [1,2,3] 
a.insert(0,'x') 
=> ['x',1,2,3] 

其中第一個參數是要插入索引,第二個是值。

17
array = ["foo"] 
array.unshift "bar" 
array 
=> ["bar", "foo"] 

被警告,這是毀滅性的!

4

您可以使用methodsolver來查找Ruby函數。

這裏是一個小劇本,

require 'methodsolver' 

solve { a = [1,2,3]; a.____(0) == [0,1,2,3] } 

運行此打印

Found 1 methods 
- Array#unshift 

可以使用安裝methodsolver

gem install methodsolver 
+0

很酷,沒想到這可能會寫'LOL – 2017-01-19 12:59:02

+0

'irb> require'methodsolver''導致'LoadError:無法從'/var/lib/gems/1.9載入這樣的文件 - method_source' ...。 1 /寶石/ methodsolver-0.0.4/LIB/methodsolver.rb:2'。 Ruby 1.9.3p484,irb 0.9.6,Ubuntu 14. – 2017-05-17 21:24:40

+0

嘗試使用'pry'而不是'irb' – akuhn 2017-05-21 02:04:21

相關問題