1. 快速獲取正則表達式的匹配值
通常我們使用正則表達式,都是先match,然后再取結果,但是這樣有時候會拋異常,看下面例子:
email.match(//)[1] # => "[email protected]"
email[//, 1] # => "[email protected]"
email.match(/(x)/)[1] # => NoMethodError [:(]
email[/(x)/, 1] # => nil
email[/([bcd]).*?([fgh])/, 2] # => "g"
上面例子中還有一種更簡單的方法,就是使用 String#[]方法,可以直接匹配正則表達式,更簡潔,雖然看起來使用了魔鬼數字。
當然你可以省略掉那個魔鬼數字,如果僅匹配一次的話:
x[/[aeiou].+?[aeiou]/] # => 'is i'
這個例子中,我們匹配規則“先匹配一個元音,然后一個輔音,再接著一個元音”。
2. Array#join!的快捷實現
我們知道Array的*操作,是將數組里面的元素成倍的增加:
但是當乘因子不是數字是字符串會出現什么效果?
h = { :name => "Fred", :age => 77 }
h.map { |i| i * "=" } * "n" # => "age=77nname=Fred"
對了,這就是join!的效果。因此可以用這種方式來快捷地實現join!操作。
3. 快速格式化十進制數字
格式化浮點數字的精度顯示通常使用sprintf這個函數,可是有一種更快捷的方式,使用字符串。
"%.2f" % money # => "9.50"
4. 快速解析字符串
在技巧3中我們看到了數字的格式化,這里就說一下字符串格式的快捷方式。
這里的意思是將”same old drag”顯示到[]中。
我們再看一下具體的格式化方法:
"%s" % x # => "
hello
”
5. 遞歸刪除文件和目錄
FileUtils提供了這種方法:
FileUtils.rm_r 'somedir'
還有一個方法是FileUtils.rm_rf,與linux上的 rm -rf 對應。
6. 快速窮舉可枚舉對象
使用*操作可以快速的窮舉出可枚舉對象中的所有元素,像Array,Hash這種對象。
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 = %w{a b c d e f g h}
b = [0, 5, 6]
a.values_at(*b).inspect # => ["a", "f", "g"]
7. 消除臨時變量
我們有時候需要寫一個臨時變量如一個臨時的Array,有一種方式可以不用單獨定義臨時變量:
當然這不是一種很好的編程習慣,建議不要大量在代碼中使用。
8. 使用非字符串或非Symbol對象作為Hash的Key
或許你從來沒有嘗試過使用非String或非Symbol對象作為Hash的Key,但是確實是可以的,有時候還蠻有用。
does[10 == 50] # => "No"
is[10 > 5] # => "Yes"
9. 使用and或or將多個操作組合到一行
這個技巧很多熟練的Ruby程序員都會使用,用來替代if和unless這種短行代碼。
%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"]
但是注意,這種方式,若and左邊表達式“queue << word”返回nil則“puts "Added to queue"”不會被執行,要慎用。不是Geek建議不要用。
10. 判斷當前Ruby解析器是否在執行自己的腳本
有時候你可能需要判斷當前的運行環境是否在自己的Ruby腳本文件中,那么可以使用:
# Do something.. run tests, call a method, etc. We're direct.
end
11. 快速地批量給變量賦值
最常用的多個變量賦值方法是:
在函數中可以批量賦值,通過傳*的參數:
a, b, c, d = args
end
還可以批量設置成員變量:
args.keys.each { |name| instance_variable_set "@" + name.to_s, args[name] }
end
12. 使用range替代復雜的數字大小比較
如果要比較if x > 1000 && x < 2000 ,可以使用如下方式替代:
puts case year
when 1970..1979: "Seventies"
when 1980..1989: "Eighties"
when 1990..1999: "Nineties"
end
13. 使用枚舉操作替換重復代碼
寫代碼最忌諱“重復”,在Ruby中有時候會require很多文件,可以使用下面的方式省去重復的require:
14. 三元操作
Ruby和其他語言一樣,有三元操作:
# Or.. an assignment based on the results of a ternary operation:
LOG.sev_threshold = ENVIRONMENT == :development ? Logger::DEBUG : Logger::INFO
15. 嵌套的三元操作
qty == 0 ? 'none' : qty == 1 ? 'one' : 'many'
# Just to illustrate, in case of confusion:
(qty == 0 ? 'none' : (qty == 1 ? 'one' : 'many'))
16. 幾種返回true,false的實現
最普通的是:
# Wayyyy too long..
if x % 2 == 0
return false
else
return true
end
end
可以簡潔一點是:
x % 2 == 0 ? false : true
end
還可以更簡潔:
# Use the logical results provided to you by Ruby already..
x % 2 != 0
end
當然,有時候你擔心返回的nil(ruby中的判定規則是nil為false,其他都為true),那么可以顯示轉換:
def contains_digits
self[/d/] ? true : false
end
end
17. 查看異常堆棧
begin
do_division_by_zero
rescue => exception
puts exception.backtrace
end
18. 將一個對象轉換為數組
*操作符可以將一個對象轉換為數組對象
=> 123456
1.9.3p125 :006 > [*items]
=> [123456]
1.9.3p125 :007 > [*items].each do | i | puts i end
123456
=> [123456]
19. 沒有begin的rescue塊
Ruby中捕獲異常的代碼是begin...rescue...:
begin
# ...
rescue
# ...
end
end
但是rescue可以沒有begin:
# ...
rescue
# ...
end
20. 塊注釋
C和Java中的塊代碼注釋是/**/,ruby中也有類似的塊注釋:
=begin
this is a block comment
You can put anything you like here!
puts "y"
=end
puts "z"
21. 拋出異常
Java中拋異常是使用throw,ruby中更靈活,可以在一行代碼中直接拋異常而不中斷當前調用棧:
h[:name].downcase # ERROR
h[:name].downcase rescue "No name" # => "No name"
|
新聞熱點
疑難解答
圖片精選