菜鸟Ruby技巧集合:序列,Array及散列

原文是说几个蠢笨的ruby技巧。

编辑推荐:Ruby入门教程与技巧大全

原文地址:http://robots.thoughtbot.com/

Ruby技巧之代码块的序列调用

 
 
 
  1. def touch_down    
  2.   yield [3, 7]    
  3.   puts "touchdown!"    
  4. end    
  5.     
  6. touch_down do |(first_down, second_down)|    
  7.   puts "#{first_down} yards on the run"    
  8.   puts "#{second_down} yards passed"    
  9. end    
  10.     
  11. => "3 yards on the run"    
  12. => "7 yards passed"    
  13. => "touchdown!"   

主要是说array在block中的使用

Ruby技巧之从array中取出元素

 
 
 
  1. >> args = [1, 2, 3]    
  2. >> first, rest = args    
  3.     
  4. >> first    
  5. => 1    
  6.     
  7. >> rest    
  8. => [2, 3]   

之前只是清楚split序列的用法,没有注意到实际上,我们可以方便的得到剩余的序列。

 
 
 
  1. Hash#fetch   
  2.  
  3. >> items = { :apples => 2, :oranges => 3 }    
  4. => items = {:apples=>2, :oranges=>3}    
  5.     
  6. >> items.fetch(:apples)    
  7. => 2    
  8.     
  9. >> items.fetch(:bananas) { |key| "We don't carry #{key}!"}    
  10. => We don't carry bananas!    
  11.  

在散列的使用的时候,fetch可能会比检查是否存在值要方便一些。

Ruby技巧之创建代码段的散列

 
 
 
  1. >> smash = Hash.new { |hash, key| hash[key] = "a #{key} just got SMASHED!" }    
  2. => {}    
  3.     
  4. >> smash[:plum] = "cannot smash."    
  5. => {:plum=>"cannot smash."}    
  6.     
  7. >> smash[:watermelon]    
  8. => {:plum=>"cannot smash.":watermelon=>"a watermelon just got SMASHED!"}    
  9.  

将代码段用于生产散列可以方便的保持一些未定义的初始值,特别是在斐波纳契计算中很适合(我没有看出来怎么用)

 
 
 
  1. Array#sort_by   
  2.  
  3. >> cars = %w[beetle volt camry]    
  4. => ["beetle""volt""camry"]    
  5.     
  6. >> cars.sort_by { |car| car.size }    
  7. => ["volt""camry""beetle"]    
  8.  

序列的sort_by方法用来对代码段的返回值排序,就如同对于Symbol#to_proc进行map或者sort

 
 
 
  1. String#present?   
  2.  
  3. >> "brain".present?    
  4. => true    
  5.     
  6. >> "".present?    
  7. => false    
  8.  

Rails的开发者可能对于blank?比较熟悉,然而对于present呢?实际上判断返回值是否正确这也是很好用的方法。

这里我确实想起来,对于find(:all)和find(:first)是否有返回值的判断的不同。还有一个
.exists?
.empty?
.blank?
.nil?

比较多见到吧。

本文来自夜鸣猪的博客:《几个Ruby用法的小技巧》

【编辑推荐】

  1. Ruby使用心得汇总:寻找高效的实现
  2. Ruby on Rails入门之道
  3. Ruby on Rails 2.3.3发布 主要修复Bug
  4. Ruby on Rails开发的五点建议
  5. 浅谈Ruby和JRuby的学习
THE END