Setting an instance variable from a block

Posted by c00lryguy on Stack Overflow See other posts from Stack Overflow or by c00lryguy
Published on 2010-06-15T19:49:36Z Indexed on 2010/06/15 19:52 UTC
Read the original article Hit count: 224

Filed under:

How would I achieve something like below so that when I set the s variable within the block, it also sets the @subject instance variable in my Topic class?

class Topic
  def subject(&blk)
    blk.call(@subject) if block_given?
    @subject unless block_given?
  end
end

my_topic = Topic.new

p my_topic.subject #=> nil

my_topic.subject do |s|
  s = ['one', 'two', 'three']
  s.pop
  p s #=> ['one', 'two']
end

p my_topic.subject #=> nil... want it to be ['one, 'two']

© Stack Overflow or respective owner

Related posts about ruby