user260818
user260818

Reputation: 1

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 comes up with an error.

    thank you...

Upvotes: 0

Views: 146

Answers (3)

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31458

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"

Upvotes: 4

Josh Lee
Josh Lee

Reputation: 177865

You're just invoking a [] class method:

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

Upvotes: 1

YOU
YOU

Reputation: 123917

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

Upvotes: 1

Related Questions