tags:

views:

58

answers:

4

Is there a shorter (and cleaner) way to write the following reader method:

class Foo
  attr_writer :bar

  def bar
    return_value = @bar
    self.bar = nil
    return_value
  end
end

Here's some output on the console to show what it does:

>> foo = Foo.new
=> #<Foo:0x1010e9cf8>
>> foo.bar
=> nil
>> foo.bar = "ok"
=> "ok"
>> foo.bar
=> "ok"
>> foo.bar
=> nil
A: 

Don't think so. Looks quite short and clean already to me!

invariant
Was imagining there could be a one-liner solution. I am definitely nit-picking!
hakanensari
It's an interesting question and I would love to be proved wrong! Am still thinking about it now...
invariant
+1  A: 
 def bar
   @bar, rv = nil, @bar
   rv
 end

or

 def bar
   (@bar, rv = nil, @bar)[1]
 end
rampion
Definitely less verbose!My only (minor) criticism would be that we're still juggling the return value via a second variable in the method. Seems there's no way to avoid that.
hakanensari
@rampion, genius! I totally ignored parallel assignment as an option! I'm glad I stayed tuned in on this to see your answer :)
macek
@smotchkkiss: You should see Wayne Conrad's - it's better.
rampion
A: 

Less clever, but perhaps more clear:

class Foo

  def initialize
    @bar = []
  end

  def bar
    @bar.pop
  end

  def bar= (obj)
    @bar[0] = obj
  end

end
steenslag
I would actually characterize it differently: more clever, but perhaps less clear.
Justice
+3  A: 
  def bar
    @bar
  ensure
    @bar = nil
  end

This can be a one-liner, if you want:

  def bar
    @bar ensure @bar = nil
  end
Wayne Conrad
I really like this.
hakanensari
Simply beautiful.
rampion