代码之家  ›  专栏  ›  技术社区  ›  John_

Ruby,我找不到下面的代码是如何工作的

  •  0
  • John_  · 技术社区  · 6 年前
    class ArrayMine < Array
    
      def join( sep = $,, format = "%s" )
    
        collect do |item|
          sprintf( format, item )
        end.join( sep )
      end
    
    end
    
    => rooms = ArrayMine[3, 4, 6]    #i couldn't understand how this line works
    
    print "We have " + rooms.join( ", ", "%d bed" ) + " rooms available."
    

    我对String也试过,但它出现了一个错误。

        thank you...
    
    3 回复  |  直到 15 年前
        1
  •  3
  •   Jonas Elfström    15 年前

    ArrayMine继承自Array,您可以像这样初始化Ruby数组。

    >> rooms = Array[3,4,6]
    => [3, 4, 6]
    

    >> rooms = [3,4,6]
    => [3, 4, 6]
    

    也很奇怪的样子 def join( sep = $,, format = "%s" ) 正在使用 pre-defined variable $, 这是打印和 Array#join

    也可以这样做

    rooms=["b",52,"s"]
    print "We have " + rooms.map{|s| s.to_s+" bed"}.join(", ") + " rooms available."
    

    你不能做你想做的事的原因 String 是因为赋值不是类方法,而是 Array 是。只是 new

    >> s = Substring.new("abcd")
    => "abcd"
    >> s.checking_next
    => "abce"
    

    在Ruby中不能重写赋值,这只是因为setter方法看起来像赋值,但实际上它们是方法调用,因此可以重写它们。 如果你觉得自己很狡猾,而且还想有类似的行为 a=SubArray[1,2,3] 你可以创建一个 << class method 像这样的:

    class Substring < String
      def next_next()
        self.next().next() 
      end
      def self.<<(val)
        self.new(val)
      end
    end 
    
    >> sub = Substring<<"abcb"
    => "abcb"
    >> sub.next_next
    => "abcd"
    >> sub<<" the good old <<"
    => "abcb the good old <<"
    >> sub.class<<"this is a new string"
    => "this is a new string"
    
        2
  •  1
  •   YOU    15 年前

    %d bed %s bed

    irb(main):053:0> rooms = ArrayMine["a","b","c"]
    => ["a", "b", "c"]
    
    irb(main):055:0> print "We have " + rooms.join( ", ", "%s bed" ) + " rooms available."
    We have a bed, b bed, c bed rooms available.=> nil
    
        3
  •  1
  •   Josh Lee    15 年前

    你只是在调用 []

    class Spam
      def self.[]( *args )
        p args
      end
    end
    
    >> Spam[3,4,5]
    [3, 4, 5]
    
    推荐文章