在学习Ruby时,我注意到在所有的例子中都没有分号。我知道只要每个陈述都在自己的行上,这就完全没问题了。但我想知道的是,你可以在Ruby中使用分号吗?
是。
Ruby不要求我们使用任何字符来分隔命令,除非我们想在一行上将多个语句链接在一起。在这种情况下,分号(;)用作分隔符。
资料来源:http://articles.sitepoint.com/article/learn-ruby-on-rails/2
作为旁注,在(j)irb会话中使用分号是有用的,以避免打印出可笑的长表达值,例如:
irb[0]> x = (1..1000000000).to_a
[printout out the whole array]
VS
irb[0]> x = (1..100000000).to_a; nil
特别适合您的MyBigORMObject.find_all调用。
分号:是的。
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
我发现分号的唯一情况是在为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
对我来说,这并没有真正消除可读性。
是的,分号可以用作Ruby中的语句分隔符。
虽然我的典型样式(以及我看到的大多数代码)在每一行上都放了一行代码,但使用;
是非常不必要的。
使用分号来保留块语法可能很有趣,如下例所示:
a = [2, 3 , 1, 2, 3].reduce(Hash.new(0)) { |h, num| h[num] += 1; h }
您维护一行代码。