我該如何實現類似於下面的內容,以便在塊內設置s
變量時,它還會在Topic類中設置@subject
實例變量?從塊中設置一個實例變量
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']
這不是說它改變了你的問題,但要記住'p s'或'puts s'返回'nil',* not *'s'。 – 2010-06-15 22:12:09