菜鳥Ruby技巧集合:序列,Array及散列
原文是說幾個蠢笨的ruby技巧。
51CTO編輯推薦:Ruby入門教程與技巧大全
原文地址:http://robots.thoughtbot.com/
Ruby技巧之代碼塊的序列調(diào)用
- 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中的使用
Ruby技巧之從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可能會比檢查是否存在值要方便一些。
Ruby技巧之創(chuàng)建代碼段的散列
- >> 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
- >> 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的開發(fā)者可能對于blank?比較熟悉,然而對于present呢?實際上判斷返回值是否正確這也是很好用的方法。
這里我確實想起來,對于find(:all)和find(:first)是否有返回值的判斷的不同。還有一個
.exists?
.empty?
.blank?
.nil?
比較多見到吧。
本文來自夜鳴豬的博客:《幾個Ruby用法的小技巧》
【編輯推薦】