幾個Ruby小技巧分享_ruby專題

來源:互聯網
上載者:User

代碼塊的序列調用

複製代碼 代碼如下:

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中取出元素

複製代碼 代碼如下:

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

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

Hash#fetch

複製代碼 代碼如下:

>> 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可能會比檢查是否存在值要方便一些。

建立程式碼片段的散列

複製代碼 代碼如下:

>> 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!"}

將程式碼片段用於生產散列可以方便的保持一些未定義的初始值,特別是在費伯納西計算中很適合(我沒有看出來怎麼用)

Array#sort_by

複製代碼 代碼如下:

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

序列的sort_by方法用來對程式碼片段的傳回值排序,就如同對於Symbol#to_proc進行map或者sort

String#present?

複製代碼 代碼如下:

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

Rails的開發人員可能對於blank?比較熟悉,然而對於present呢?實際上判斷傳回值是否正確這也是很好用的方法。

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

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

比較多見到吧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.