欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

幾個Ruby小技巧分享

 更新時間:2015年05月26日 09:48:15   投稿:junjie  
這篇文章主要介紹了幾個Ruby小技巧分享,本文講解了代碼塊的序列調(diào)用、主要是說array在block中的使用、Hash#fetch、創(chuàng)建代碼段的散列等小技巧,需要的朋友可以參考下

代碼塊的序列調(diào)用

復(fù)制代碼 代碼如下:

def touch_down 
  yield [3, 7] 
  puts "touchdown!" 
end 
 
touch_down do |(first_down, second_down)| 
  puts "#{first_down} yards on the run" 
  puts "#{second_down} yards passed" 
end 
 
=> "3 yards on the run" 
=> "7 yards passed" 
=> "touchdown!" 

主要是說array在block中的使用

從array中取出元素

復(fù)制代碼 代碼如下:

>> args = [1, 2, 3] 
>> first, rest = args 
 
>> first 
=> 1 
 
>> rest 
=> [2, 3] 

之前只是清楚split序列的用法,沒有注意到實際上,我們可以方便的得到剩余的序列。

Hash#fetch

復(fù)制代碼 代碼如下:

>> items = { :apples => 2, :oranges => 3 } 
=> items = {:apples=>2, :oranges=>3} 
 
>> items.fetch(:apples) 
=> 2 
 
>> items.fetch(:bananas) { |key| "We don't carry #{key}!"} 
=> We don't carry bananas! 

在散列的使用的時候,fetch可能會比檢查是否存在值要方便一些。

創(chuàng)建代碼段的散列

復(fù)制代碼 代碼如下:

>> smash = Hash.new { |hash, key| hash[key] = "a #{key} just got SMASHED!" } 
=> {} 
 
>> smash[:plum] = "cannot smash." 
=> {:plum=>"cannot smash."} 
 
>> smash[:watermelon] 
=> {:plum=>"cannot smash.", :watermelon=>"a watermelon just got SMASHED!"}

將代碼段用于生產(chǎn)散列可以方便的保持一些未定義的初始值,特別是在斐波納契計算中很適合(我沒有看出來怎么用)

Array#sort_by

復(fù)制代碼 代碼如下:

>> cars = %w[beetle volt camry] 
=> ["beetle", "volt", "camry"] 
 
>> cars.sort_by { |car| car.size } 
=> ["volt", "camry", "beetle"] 

序列的sort_by方法用來對代碼段的返回值排序,就如同對于Symbol#to_proc進(jìn)行map或者sort

String#present?

復(fù)制代碼 代碼如下:

>> "brain".present? 
=> true 
 
>> "".present? 
=> false 

Rails的開發(fā)者可能對于blank?比較熟悉,然而對于present呢?實際上判斷返回值是否正確這也是很好用的方法。

這里我確實想起來,對于find(:all)和find(:first)是否有返回值的判斷的不同。還有一個

.exists?
.empty?
.blank?
.nil?

比較多見到吧

相關(guān)文章

最新評論