ruby 方法(3)

symbolize_keys

hash = { 'name' => 'Rob', 'age' => '28' }

hash.symbolize_keys
#=> { name: "Rob", age: "28" }

try

[:a, :b, :c].try(:at,1)

Person.try(:find, 1)

@people.try(:collect) {|p| p.name}

@person.try { |p| "#{p.first_name} #{p.last_name}"}

 

touch  更新(update_at)时间

User.last.touch

 

extract(*keys)

  {:a =>1, :b => 2, :c => 3}.extract!(:a)  =>   {:a => 1} 返回删除值,原hash的值改变

slice(*keys)

  {:a =>1, :b => 2, :c => 3}.slice(:a)  =>   {:a => 1} 返回所选值,原hash的值不变

cache  加缓存

reject 

  (1..10).reject {|i| i%3 == 0}    

    => [1,2,4,5,7,8,10]

  {a: 'first',  b: '',  c: 'third'}.reject{|k , v| v.empty?}  

    => {a: 'first',  c: 'third'}

strftime

  Time.now.strftime("printed on %m/%d/%Y")

  =>  printed on 04/22/2014

Hash

  Hash["a", 100, "b", 200]

  Hash["a" => 100, "b" => 200]

     Hash[one:1, two: 2]

posted on 2014-04-22 17:32  qinyan20  阅读(230)  评论(0编辑  收藏  举报