开发者

Ruby , I couldn't find how the following code actually works

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."

i have tried the same with String, but it come开发者_StackOverflow中文版s up with an error.

    thank you...


ArrayMine inherits from Array and you can initialize Ruby arrays like that.

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

is the same as

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

Also the quite strange looking def join( sep = $,, format = "%s" ) is using the pre-defined variable $, that is the output field separator for the print and Array#join.

It could also have been done like this

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

The reason you can't do what you are trying to do with String is because assignment is not a class method but [] on Array is. Just new it instead.

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

You can't override assignment in Ruby, it's only so that setter methods looks like assignment but they are actually method calls and as such they can be overridden. If you are feeling like being tricky and still want a similar behaviour as a=SubArray[1,2,3] you could create a << class method something like this:

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"


For String, change %d bed to %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


You're just invoking a [] class method:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜