代码之家  ›  专栏  ›  技术社区  ›  Mark Szymanski

你能在Ruby中用分号吗?

  •  71
  • Mark Szymanski  · 技术社区  · 15 年前

    学习Ruby时,我注意到在所有示例中都没有分号。我知道,只要每一句话都有自己的台词,这就非常好。但我想知道的是, 可以 在Ruby中使用分号?

    6 回复  |  直到 7 年前
        1
  •  93
  •   David Brown Muad'Dib    15 年前

    对。

    Ruby不要求我们使用任何字符来分隔命令,除非我们想在一行上将多个语句链接在一起。在这种情况下,分号(;)用作分隔符。

    来源: http://articles.sitepoint.com/article/learn-ruby-on-rails/2

        2
  •  29
  •   Nick Messick    7 年前

    作为补充说明,在(j)IRB会话中使用分号有助于避免打印出荒谬的长表达式值,例如。

    irb[0]> x = (1..1000000000).to_a
    [printout out the whole array]
    

    VS

    irb[0]> x = (1..100000000).to_a; nil
    

    特别适合你的MyBigormObject。查找所有调用。

        3
  •  5
  •   Sophia Feng    10 年前

    分号:是的。

    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
    
        4
  •  3
  •   ryan    14 年前

    我遇到的唯一一种情况是,分号在为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
    

    对我来说,这并不能真正消除可读性。

        5
  •  2
  •   wkl    15 年前

    是的,分号可以在Ruby中用作语句分隔符。

    尽管我的典型风格 我看到的代码)在每行上放置一行代码,因此 ; 很不必要。

        6
  •  0
  •   Tom cmoron    9 年前

    使用分号保留块语法可能很有趣,如本例所示:

    a = [2, 3 , 1, 2, 3].reduce(Hash.new(0)) { |h, num| h[num] += 1; h }
    

    您维护一行代码。

    推荐文章