Ruby Tricks 大全

本文介绍了一系列Ruby编程语言中的实用技巧,包括字符串与数组的操作、默认返回值的应用、单行方法的编写、格式化数值及字符串的方法等。文章还探讨了如何使用范围替代复杂的数值比较、查看异常的完整回溯路径、利用rescue处理异常情况等内容。

下面所有用法都是1.8.6里的,同时欢迎补充1.9和rails里面的tricks...


一.神奇的*
1.String#*

  "Hello!" * 2
 #=> "Hello!Hello!"
 


2.Array#*

   %w{one two three} * 2
  #=> ["one", "two", "three", "one", "two", "three"]
 


3.Shortcut for Array#join

   %w{one two three} * ", "
  #=> "one, two, three"
 

 

 %w{this is a test} * ", "                 # => "this, is, a, test"
 h = { :name => "Fred", :age => 77 }
 h.map { |i| i * "=" } * "&"              # => "age=77&name=Fred"
 


4.explore to enumerator

  a = %w{a b}
b = %w{c d}
[a + b]                              # => [["a", "b", "c", "d"]]
[*a + b]                             # => ["a", "b", "c", "d"]
 

 

 a = { :name => "Fred", :age => 93 }
[a]                                  # => [{:name => "Fred", :age =>93}]
[*a]                                 # => [[:name, "Fred"], [:age, 93]]
  

 

  a = %w{a b c d e f g h}
b = [0, 5, 6]
a.values_at(*b).inspect              # => ["a", "f", "g"]
 

 

  fruit = ["apple","red","banana","yellow"]
#=> ["apple", "red", "banana", "yellow"]

Hash[*fruit]    
#=> {"apple"=>"red", "banana"=>"yellow"}
 


5.*arg作为参数

 def my_method(*args)
  a, b, c, d = args
end 


6.Object#*

 match, text, number = *"Something 981".match(/([A-z]*) ([0-9]*)/)

 

  a, b, c = *('A'..'Z')

Job = Struct.new(:name, :occupation)
tom = Job.new("Tom", "Developer")
name, occupation = *tom



二.默认返回值.
Array#[]在index超出array范围时会默认返回nil(如果不想要默认值或是要扩展默认值可以用Array#fetch):

 irb(main):074:0> a = [1 ,2, 3]
=> [1, 2, 3]
irb(main):075:0> a[5]
=> nil
irb(main):076:0> a.fetch(8)
IndexError: index 8 out of array
        from (irb):76:in `fetch'
        from (irb):76
        from :0
irb(main):077:0> a.fetch(8,nil)
=> nil
irb(main):078:0> a.fetch(8,"index out of array!")
=> "index out of array!"
 


Hash也是在key不存在的时候返回默认值nil,也可以自己设置默认值或default_proc

 irb(main):008:0> hash = Hash.new{|hash,key| hash[key] = key.upcase if key.kind_o
f? String}
=> {}
irb(main):009:0> hash[1]
=> nil
irb(main):010:0> hash["key"]
=> "KEY"



Regex也可以有默认返回值:

 email = "Fred Bloggs <fred@bloggs.com>"
email.match(/<(.*?)>/)[1]            # => "fred@bloggs.com"
email[/<(.*?)>/, 1]                  # => "fred@bloggs.com"
email.match(/(x)/)[1]                # => NoMethodError 
email[/(x)/, 1]                      # => nil


当然最强大的还是method_missing了....

三.习以为常的single line method
在ruby里一行代码完成一个方法是很常见的....这主要归功于enumerable模块里面定义的神奇方法,还有if,unless等

 queue = []
%w{hello x world}.each do |word|
  queue << word and puts "Added to queue" unless word.length <  2
end
puts queue.inspect

# Output:
#   Added to queue
#   Added to queue
#   ["hello", "world"]



三元操作符:

 def is_odd(x)
  x % 2 == 0 ? false : true
end

 

 all?, any?, collect, detect, each_cons, each_slice,
 each_with_index, entries, enum_cons, enum_slice, enum_with_index,
 find, find_all, grep, include?, inject, inject, map, max, member?,
 min, partition, reject, select, sort, sort_by, to_a, to_set, zip

 

 

  p queue = %w{hello x world}.select { |word| word.length >= 2 }


四.其他
1.Format decimal amounts quickly

 money = 9.5
"%.2f" % money                       # => "9.50"


2.Surround text quickly

"[%s]" % "same old drag"             # => "[same old drag]"


3.Delete trees of files

require 'fileutils'
FileUtils.rm_r 'somedir'


4.Cut down on local variable definitions

 (z ||= []) << 'test'



5.Using non-strings or symbols as hash keys

 does = is = { true => 'Yes', false => 'No' }
does[10 == 50]                       # => "No"
is[10 > 5]                           # => "Yes"



6.Do something only if the code is being implicitly run, not required

 if __FILE__ == $0
  # Do something.. run tests, call a method, etc. We're direct.
end



7.Use ranges instead of complex comparisons for numbers

#让 if x > 1000 && x < 2000 歇菜吧
 year = 1972
puts  case year
        when 1970..1979: "70后"
        when 1980..1989: "80后"
        when 1990..1999: "90后"
      end



8.See the whole of an exception's backtrace

  def do_division_by_zero; 5 / 0; end
begin
  do_division_by_zero
rescue => exception
  puts exception.backtrace
end



9.Rescue blocks don't need to be tied to a 'begin'

 def x
  begin
    # ...
  rescue
    # ...
  end
end

 

 def x
  # ...
rescue
  # ...
end


10.Rescue to the rescue

 h = { :age => 10 }
h[:name].downcase                         # ERROR
h[:name].downcase rescue "No name"        # => "No name"


11.convert a Fixnum into any base up to 36

  >> 1234567890.to_s(2)
=> "1001001100101100000001011010010"

>> 1234567890.to_s(8)
=> "11145401322"

>> 1234567890.to_s(16)
=> "499602d2"

>> 1234567890.to_s(24)
=> "6b1230i"

>> 1234567890.to_s(36)
=> "kf12oi"



12.module_function

#让module更class
  module M
  def not!
    'not!'
  end
  module_function :not!
end

class C
  include M

  def fun
    not!
  end
end

M.not!     # => 'not!
C.new.fun  # => 'not!'
C.new.not! # => NoMethodError: private method `not!' called for #<C:0x1261a00>

 

 module M
  module_function

  def not!
    'not!'
  end

  def yea!
    'yea!'
  end
end


class C
  include M

  def fun
    not! + ' ' + yea!
  end
end
M.not!     # => 'not!'
M.yea!     # => 'yea!'
C.new.fun  # => 'not! yea!'


13.use  here document and any character you want to delimit strings 

 message = "My message"
contrived_example = "<div id=\"contrived\">#{message}</div>"
contrived_example = %{<div id="contrived-example">#{message}</div>}
contrived_example = %[<div id="contrived-example">#{message}</div>]
sql = %{
    SELECT strings 
    FROM complicated_table
    WHERE complicated_condition = '1'
}
sql = <<-SQL
    SELECT strings 
    FROM complicated_table
    WHERE complicated_condition = '1'
SQL


14.define_method

 ((0..9).each do |n|
    define_method "press_#{n}" do
      @number = @number.to_i * 10 + n
    end
  end


15.create Class at run time..

class Array
#define Array#rand
  def rand
    self.fetch Kernel.rand(self.size)
  end
end
class RandomSubclass < [Array, Hash, String, Fixnum, Float, TrueClass].rand

end

RandomSubclass.superclass # could output one of 6 different classes.


16.call private methods of class with send.

 class A

  private

  def my_private_method
    puts 'private method called'
  end
end

a = A.new
a.my_private_method # Raises exception saying private method was called
a.send :my_private_method # Calls my_private_method and prints private method called'


16.__END__

p DATA #=>#<File:tt.rb>
p DATA.read #=> "line1\nline2\nline3"

__END__
line1
line2
line3


17.FX和NS两位大神提供...目前不知道是做什么的.......

gets gets

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值