I am having trouble passing values to an array of a new instance of the
class Item that I have created. The following codse does not fille the
flags array with the value 'container'.
class Item
attr_accessor :inum, :name, :description, :slot, :flags, :items
I am having trouble passing values to an array of a new instance of the
class Item that I have created. The following codse does not fille the
flags array with the value 'container'.
class Item
attr_accessor :inum, :name, :description, :slot, :flags, :items
My question is, how do I modify the first bit of code to allow passing
values to the array of the new instance of the class Item?
--
Posted via http://www.ruby-forum.com/.
I am having trouble passing values to an array of a new instance of the
class Item that I have created. The following codse does not fille the
flags array with the value 'container'.
class Item
attr_accessor :inum, :name, :description, :slot, :flags, :items
i.e. copy an array passed via parameter "items". If you want to
explicitly create an array you can do
@items = [].concat items
If you do not always pass an Array you can do
@items = []
case items
when String @items << items
when Array @items.concat items
when Enumerable @items.concat items.to_a
else
raise ArgumentError, "Dunno what to do with %p" % items
end
end
def is_container
return true if flags.include?(container)
end
You can simply do
def is_container?
flags.include? container
end
end
Item.new("0007", "crate", "A large crate.\r\n", ":none", "container",
"")
However when I use the code below, I am able to add the value
'container' to the flags array.
Note though that the code above only appends a single Array to the Array - it does not "push items into the array"! For that you need #concat as I have shown.
Kind regards
robert
···
On 08/30/2010 04:56 PM, Jonathan Allen wrote:
Robert Klemme wrote:
If you do not always pass an Array you can do
@items = []
@items<< items
Thanks Robert. I didn't think about pushing the items into the array
from within the actual code for the class Item itself.
This worked just the way I was hoping. Thanks again!