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
def initialize( inum, name, description, slot, flags, items )
@inum = inum
@name = name
@description = description
@slot = slot
@flags = []
@items = []
end
def is_container
return true if 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.
$rooms[(“0001”)].item(“crate”).flags << “container”
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?
If I’m understanding right, the modifications I made to your code below
should do what you want
On Mon, Aug 30, 2010 at 9:21 AM, Jonathan A. <
Robert K. 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!
2010/8/30 Jonathan A. [email protected]:
@name = name
@description = description
@slot = slot
@flags = []
@items = []
You could do
@items = items.dup
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
$rooms[(“0001”)].item(“crate”).flags << “container”
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?
Hope the suggestions help.
Kind regards
robert
On 08/30/2010 04:56 PM, Jonathan A. wrote:
Robert K. 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!
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 Mon, Aug 30, 2010 at 3:21 PM, Jonathan A.
[email protected] wrote:
def is_container
return true if flags.include?(container)
end
end
Apart from all the other suggestions, you should change the container
above to “container”.
Jesus.