当前位置 博文首页 > 几个Ruby小技巧分享

    几个Ruby小技巧分享

    作者:admin 时间:2021-02-07 06:05

    代码块的序列调用

    复制代码 代码如下:

    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?

    比较多见到吧

    js
下一篇:没有了