国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Ruby > 正文

Ruby編程的21個(gè)小技巧介紹

2020-02-24 15:41:13
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本篇文章主要講Ruby編程的21個(gè)小技巧介紹,有些代碼小編也不太理解,很多是在網(wǎng)上借鑒其他人的。

1. 快速獲取正則表達(dá)式的匹配值

通常我們使用正則表達(dá)式,都是先match,然后再取結(jié)果,但是這樣有時(shí)候會(huì)拋異常,看下面例子:

?


email = "Fred Bloggs "

?

email.match(//)[1] # => "fred@bloggs.com"

email[//, 1] # => "fred@bloggs.com"

email.match(/(x)/)[1] # => NoMethodError [:(]

email[/(x)/, 1] # => nil

email[/([bcd]).*?([fgh])/, 2] # => "g"

?

上面例子中還有一種更簡(jiǎn)單的方法,就是使用 String#[]方法,可以直接匹配正則表達(dá)式,更簡(jiǎn)潔,雖然看起來(lái)使用了魔鬼數(shù)字。
當(dāng)然你可以省略掉那個(gè)魔鬼數(shù)字,如果僅匹配一次的話:

?


x = 'this is a test'

?

x[/[aeiou].+?[aeiou]/] # => 'is i'

?

這個(gè)例子中,我們匹配規(guī)則“先匹配一個(gè)元音,然后一個(gè)輔音,再接著一個(gè)元音”。

2. Array#join!的快捷實(shí)現(xiàn)

我們知道Array的*操作,是將數(shù)組里面的元素成倍的增加:

?


[1, 2, 3] * 3 == [1, 2, 3, 1, 2, 3, 1, 2, 3]

?

但是當(dāng)乘因子不是數(shù)字是字符串會(huì)出現(xiàn)什么效果?

?


%w{this is a test} * ", " # => "this, is, a, test"

?

h = { :name => "Fred", :age => 77 }

h.map { |i| i * "=" } * "n" # => "age=77nname=Fred"

?

對(duì)了,這就是join!的效果。因此可以用這種方式來(lái)快捷地實(shí)現(xiàn)join!操作。

3. 快速格式化十進(jìn)制數(shù)字

格式化浮點(diǎn)數(shù)字的精度顯示通常使用sprintf這個(gè)函數(shù),可是有一種更快捷的方式,使用字符串。

?


money = 9.5

?

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

?

4. 快速解析字符串

在技巧3中我們看到了數(shù)字的格式化,這里就說(shuō)一下字符串格式的快捷方式。

?


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

?

這里的意思是將”same old drag”顯示到[]中。
我們?cè)倏匆幌戮唧w的格式化方法:

?


x = %w{p hello p}

?

"%s" % x # => "

hello

?

5. 遞歸刪除文件和目錄

FileUtils提供了這種方法:

?


require 'fileutils'

?

FileUtils.rm_r 'somedir'

?

還有一個(gè)方法是FileUtils.rm_rf,與linux上的 rm -rf 對(duì)應(yīng)。

6. 快速窮舉可枚舉對(duì)象

使用*操作可以快速的窮舉出可枚舉對(duì)象中的所有元素,像Array,Hash這種對(duì)象。

?


a = %w{a b}

?

b = %w{c d}

[a + b]????????????????????????????? # => [["a", "b", "c", "d"]]

[*a + b]???????????????????????????? # => ["a", "b", "c", "d"]

?

這里*操作符的優(yōu)先級(jí)低于+操作符。

?


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"]

?

7. 消除臨時(shí)變量

我們有時(shí)候需要寫(xiě)一個(gè)臨時(shí)變量如一個(gè)臨時(shí)的Array,有一種方式可以不用單獨(dú)定義臨時(shí)變量:

?


(z ||= [])

?

當(dāng)然這不是一種很好的編程習(xí)慣,建議不要大量在代碼中使用。

8. 使用非字符串或非Symbol對(duì)象作為Hash的Key

或許你從來(lái)沒(méi)有嘗試過(guò)使用非String或非Symbol對(duì)象作為Hash的Key,但是確實(shí)是可以的,有時(shí)候還蠻有用。

?


does = is = { true => 'Yes', false => 'No' }

?

does[10 == 50]?????????????????????? # => "No"

is[10 > 5]?????????????????????????? # => "Yes"

?

9. 使用and或or將多個(gè)操作組合到一行

這個(gè)技巧很多熟練的Ruby程序員都會(huì)使用,用來(lái)替代if和unless這種短行代碼。

?


queue = []

?

%w{hello x world}.each do |word|

? queue

end

puts queue.inspect


# Output:

#?? Added to queue

#?? Added to queue

#?? ["hello", "world"]

?

但是注意,這種方式,若and左邊表達(dá)式“queue

10. 判斷當(dāng)前Ruby解析器是否在執(zhí)行自己的腳本

有時(shí)候你可能需要判斷當(dāng)前的運(yùn)行環(huán)境是否在自己的Ruby腳本文件中,那么可以使用:

?


if __FILE__ == $0

?

? # Do something.. run tests, call a method, etc. We're direct.

end

?

11. 快速地批量給變量賦值

最常用的多個(gè)變量賦值方法是:

?


a, b, c, d = 1, 2, 3, 4

?

在函數(shù)中可以批量賦值,通過(guò)傳*的參數(shù):

?


def my_method(*args)

?

? a, b, c, d = args

end

?

還可以批量設(shè)置成員變量:

?


def initialize(args)

?

? args.keys.each { |name| instance_variable_set "@" + name.to_s, args[name] }

end

?

12. 使用range替代復(fù)雜的數(shù)字大小比較

如果要比較if x > 1000 && x

?


year = 1972

?

puts? case year

??????? when 1970..1979: "Seventies"

??????? when 1980..1989: "Eighties"

??????? when 1990..1999: "Nineties"

????? end

?

13. 使用枚舉操作替換重復(fù)代碼

寫(xiě)代碼最忌諱“重復(fù)”,在Ruby中有時(shí)候會(huì)require很多文件,可以使用下面的方式省去重復(fù)的require:

?


%w{rubygems daemons eventmachine}.each { |x| require x }

?

14. 三元操作

Ruby和其他語(yǔ)言一樣,有三元操作:

?


puts x == 10 ? "x is ten" : "x is not ten"

?


# Or.. an assignment based on the results of a ternary operation:

LOG.sev_threshold = ENVIRONMENT == :development ? Logger::DEBUG : Logger::INFO

?

15. 嵌套的三元操作

?


qty = 1

?

qty == 0 ? 'none' : qty == 1 ? 'one' : 'many'

# Just to illustrate, in case of confusion:

(qty == 0 ? 'none' : (qty == 1 ? 'one' : 'many'))

?

16. 幾種返回true,false的實(shí)現(xiàn)

最普通的是:

?


def is_odd(x)

?

? # Wayyyy too long..

? if x % 2 == 0

??? return false

? else

??? return true

? end

end

?

可以簡(jiǎn)潔一點(diǎn)是:

?


def is_odd(x)

?

? x % 2 == 0 ? false : true

end

?

還可以更簡(jiǎn)潔:

?


def is_odd(x)

?

? # Use the logical results provided to you by Ruby already..

? x % 2 != 0

end

?

當(dāng)然,有時(shí)候你擔(dān)心返回的nil(ruby中的判定規(guī)則是nil為false,其他都為true),那么可以顯示轉(zhuǎn)換:

?


class String

?

? def contains_digits

??? self[/d/] ? true : false

? end

end

?

17. 查看異常堆棧

?


def do_division_by_zero; 5 / 0; end

?

begin

? do_division_by_zero

rescue => exception

? puts exception.backtrace

end

?

18. 將一個(gè)對(duì)象轉(zhuǎn)換為數(shù)組

*操作符可以將一個(gè)對(duì)象轉(zhuǎn)換為數(shù)組對(duì)象

?


1.9.3p125 :005 > items = 123456

?

?=> 123456

1.9.3p125 :006 > [*items]

?=> [123456]

1.9.3p125 :007 > [*items].each do | i | puts i end

123456

?=> [123456]

?

19. 沒(méi)有begin的rescue塊

Ruby中捕獲異常的代碼是begin...rescue...:

?


def x

?

? begin

??? # ...

? rescue

??? # ...

? end

end

?

但是rescue可以沒(méi)有begin:

?


def x

?

? # ...

rescue

? # ...

end

?

20. 塊注釋

C和Java中的塊代碼注釋是/**/,ruby中也有類(lèi)似的塊注釋:

?


puts "x"

?

=begin

? this is a block comment

? You can put anything you like here!


? puts "y"

=end

puts "z"

?

21. 拋出異常

Java中拋異常是使用throw,ruby中更靈活,可以在一行代碼中直接拋異常而不中斷當(dāng)前調(diào)用棧:

?


h = { :age => 10 }

?

h[:name].downcase???????????????????????? # ERROR

h[:name].downcase rescue "No name"??????? # => "No name"

以上就是Ruby編程的21個(gè)小技巧介紹,希望小編整理的相關(guān)知識(shí)和資料都對(duì)你們有所幫助,更多內(nèi)容請(qǐng)繼續(xù)關(guān)注武林技術(shù)頻道網(wǎng)站!

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 东明县| 伊春市| 涿鹿县| 六枝特区| 泰宁县| 永新县| 德钦县| 凤台县| 岫岩| 松原市| 乌拉特前旗| 大荔县| 抚顺市| 准格尔旗| 满洲里市| 萝北县| 阿勒泰市| 静宁县| 陆川县| 鹤岗市| 卫辉市| 大名县| 浦江县| 红河县| 绥棱县| 大新县| 台中市| 神池县| 广平县| 乌恰县| 特克斯县| 繁峙县| 电白县| 扬州市| 枝江市| 永康市| 武宁县| 孙吴县| 林周县| 醴陵市| 弥勒县|