开发者

attr_accessor for array?

开发者 https://www.devze.com 2023-01-16 00:26 出处:网络
I want to have an array as a instance variable using attr_accessor. But isn\'t attr_accessor only for strings?

I want to have an array as a instance variable using attr_accessor.

But isn't attr_accessor only for strings?

How do I use it on an array?

UPDATE:

Eg. If you want:

object.array = "cat"
object.array = "d开发者_Python百科og"
pp object.array
=> ["cat", "dog"]

Then you have to create those methods yourself?


class SomeObject
  attr_accessor :array

  def initialize
    self.array = []
  end
end

o = SomeObject.new

o.array.push :a
o.array.push :b
o.array << :c
o.array.inspect   #=> [:a, :b, :c]


Re your update:

Although you can implement a class which acts as you describe, it is quite unusual, and will probably confuse anyone using the class.

Normally accessors have setters and getters. When you set something using the setter, you get the same thing back from the getter. In the example below, you get something totally different back from the getter. Instead of using a setter, you should probably use an add method.

class StrangePropertyAccessorClass

  def initialize
    @data = []
  end

  def array=(value)   # this is bad, use the add method below instead
    @data.push(value)
  end

  def array
    @data
  end

end

object = StrangePropertyAccessorClass.new

object.array = "cat"
object.array = "dog"
pp object.array

The add method would look like this:

  def add(value)
    @data.push(value)
  end

...

object.add "cat"
object.add "dog"
pp object.array


It works for me:

class Foo

  attr_accessor :arr

  def initialize() 
    @arr = [1,2,3]
  end

end

f = Foo.new
p f.arr

Returns the following

$ ruby /tmp/t.rb
[1, 2, 3]
$


I think there is a case for this usage. Consider

begin
  result = do_something(obj)
  # I can't handle the thought of failure, only one result matters!
  obj.result = result
rescue
  result = try_something_else(obj)
  # okay so only this result matters!
  obj.result = result
end

And then later

# We don't really care how many times we tried only the last result matters
obj.result

And then for the pro's we have

# How many times did we have to try?
obj.results.count

So, I would:

attr_accessor :results

def initialize
  @results = []
end

def result=(x)
  @results << x
end

def result
  @results.last
end

In this way result behaves as you would expect, but you also get the benefit of accessing the past values.

0

精彩评论

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