In addition to these solutions, if you know that ivar is going to remain String / Array / Hash, no matter what you do, you can do the following:
class Topic def subject @subject ||= 'sane default' if block_given? then yield(@subject) else @subject end end end t = Topic.new t.subject { |s| s.replace 'fancy stuff' }
Although from what I think you are doing, this is the most suitable code:
class Topic def subject return @subject unless block_given? @subject = yield(@subject) end end t = Topic.new t.subject { |s| 'fancy stuff' } t.subject { |s| "very #{s}" } t.subject
Alternatively, you could do this without a block:
class Topic def subject(value = nil) @subject = value % @subject if value @subject = yield @subject if block_given? @subject end end t = Topic.new t.subject 'fancy stuff'
Keep in mind that the ps expression you use returns nil .
source share