在學習Ruby時,我注意到在所有例子中都沒有分號。我知道,只要每一項聲明都是按照自己的路線行事的話,這就完全正常了。但是我想知道的是,可以使用在Ruby中使用分號嗎?你可以在Ruby中使用分號嗎?
在此先感謝!
在學習Ruby時,我注意到在所有例子中都沒有分號。我知道,只要每一項聲明都是按照自己的路線行事的話,這就完全正常了。但是我想知道的是,可以使用在Ruby中使用分號嗎?你可以在Ruby中使用分號嗎?
在此先感謝!
是的。
Ruby不需要我們使用任何字符來分隔命令,除非我們想在一行中鏈接多個語句。在這種情況下,使用分號(;)作爲分隔符。
來源:http://articles.sitepoint.com/article/learn-ruby-on-rails/2
真棒,謝謝! – 2010-10-17 15:49:30
但我應該使用分號嗎? – rocketspacer 2017-04-20 15:53:19
是的,分號可以用作Ruby中的語句分隔符。
雖然我的典型風格(和大多數代碼我看到)每行放置一行代碼,所以使用;
是相當多的。
作爲邊注,它在你的(j)至使用分號IRB會話以避免打印出一個可笑長表達式值,例如有用
irb[0]> x = (1..1000000000).to_a
[printout out the whole array]
VS
irb[0]> x = (1..100000000).to_a; 1
1
尼斯尤其是對你的MyBigORMObject.find_all電話。
我遇到分號的唯一情況是有用的是爲attr_reader聲明別名方法。
考慮下面的代碼:
attr_reader :property1_enabled
attr_reader :property2_enabled
attr_reader :property3_enabled
alias_method :property1_enabled?, :property1_enabled
alias_method :property2_enabled?, :property2_enabled
alias_method :property3_enabled?, :property3_enabled
用分號,我們可以減少這種下降3行:
attr_reader :property1_enabled; alias_method :property1_enabled?, :property1_enabled
attr_reader :property2_enabled; alias_method :property2_enabled?, :property2_enabled
attr_reader :property3_enabled; alias_method :property3_enabled?, :property3_enabled
對我來說這並沒有真正從可讀性帶走。
分號:是的。
irb(main):018:0> x = 1; c = 0
=> 0
irb(main):019:0> x
=> 1
irb(main):020:0> c
=> 0
你甚至可以運行由分號在一行代碼迴路分隔的多個命令
irb(main):021:0> (c += x; x += 1) while x < 10
=> nil
irb(main):022:0> x
=> 10
irb(main):023:0> c
=> 45
它可以是有趣的,用分號來保護塊的語法如下例:
a = [2, 3 , 1, 2, 3].reduce(Hash.new(0)) { |h, num| h[num] += 1; h }
您維護一行代碼。
對於那裏的Ruby人:應該使用分號嗎?這樣做有益嗎?我知道,當我編寫Ruby代碼時,我反思性地添加它們。 – 2010-10-17 15:34:29
@Andy不要使用分號,除非你想在同一行放置多個語句,[你應該避免這樣做](http://www.caliban.org/ruby/rubyguide.shtml#semicolon)。 – 2010-10-17 19:37:16
@Yaser:我需要分號。因爲在沒有分號的行上有函數時,vim爲我自動生成一個函數,我不想發生這種情況。 – 2010-10-17 19:40:52