But why would I want to pop it out and return it?
這裏是您可以使用pop()方法做一個例子:
dispatcher = {
"+" => lambda {|x, y| x+y},
"-" => lambda {|x, y| x-y},
"*" => lambda {|x, y| x*y},
}
print "Enter two values followed by an operation(+, -, *): "
input_arr = gets.chomp.split()
func = dispatcher[input_arr.pop] #Remove the operation from the array, so that you can...
input_arr = input_arr.map {|val| val.to_i} #...call to_i() on the rest of the elements
result = func.call(*input_arr)
puts result
--output:--
$ ruby my_prog.rb
Enter two values followed by an operation(+, -, *): 3 2 +
5
~/ruby_programs$ ruby my_prog.rb
Enter two values followed by an operation(+, -, *): 3 2 -
1
~/ruby_programs$ ruby my_prog.rb
Enter two values followed by an operation(+, -, *): 3 2 *
6
當你在學習編程語言時,你正在學習技巧。你可能無法想象一個技巧是如何有用的,但隨着你獲得更多的經驗,你會想到一個編程問題,並希望你知道的相關技巧將浮現在腦海。另外,你應該知道pop()和shift()有不同的後果。將一個元素從數組的前面移開(),因爲所有其他元素都必須移過來,效率會低得多。如果你的陣列有1000萬個元素呢?然後彈出()結束元素很容易,但將元素從前面移開對於效率而言是災難性的。 Ruby借用了很多東西的編程語言Perl以pop()和shift()同樣高效的方式創建了數組,但我不相信ruby採用類似的策略。
除了彈出/推動速度更快這一事實,它真的是你想要在開始還是結束時添加元素 – 2014-08-30 23:17:21