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

时间:2010-01-28 09:41:37

标签: ruby

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 个答案:

答案 0 :(得分:3)

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"

答案 1 :(得分:1)

对于字符串,将%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

答案 2 :(得分:1)

您只是调用[]类方法:

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