Yield self if block_given?

class AngstyNamedPerson
attr_reader :name

@@hated_names = %w(Leroy Sparkles Thaddius)

def name=(new_name)
@name = new_name
raise “I have probems with being named #{@name}.” if
@@hated_names.include? new_name
end

def initialize(name)
@name = name
end

def transactionally(&block)
old_name = @name
begin
yield self if block_given?
rescue
@name = old_name
end
end
end

mr_pibbles = AngstyNamedPerson.new(‘Mr. Pibbles’)


In the code above, what’s “yied self if block_given?” in the function
of transactionally?
I can’t understand for the “self”.

Please help with it.
Thanks.

I tried below, it can work,

irb(main):001:0> class Myclass
irb(main):002:1> def mya
irb(main):003:2> yield self if block_given?
irb(main):004:2> end
irb(main):005:1> def myb
irb(main):006:2> puts “it’s myb”
irb(main):007:2> end
irb(main):008:1> end
=> nil
irb(main):009:0>
irb(main):010:0* x=Myclass.new
=> #Myclass:0x83f81b0
irb(main):012:0> x.mya { puts “a”}
a
=> nil
irb(main):013:0> x.mya { |c| c.myb }
it’s myb
=> nil


in the code above, what’s “c” there?
does it mean the instance of x itself?

Thanks again.

Hi

in the code above, what’s “c” there?
does it mean the instance of x itself?

Yes it does.
Try
x.mya {|c| p c}


Ayumu AIZAWA

Hi,

Am Freitag, 01. Jan 2010, 23:54:12 +0900 schrieb Ruby N.:

@name = name

end

mr_pibbles = AngstyNamedPerson.new ‘Mr. Pibbles’

In the code above, what’s “yied self if block_given?” in the function
of transactionally?
I can’t understand for the “self”.

I would like to tell it superfluous as in all regular cases the
caller yet has the object in a variable.

p.transactionally { |p_|
p.equal? p_ or raise “wrong library”
}

It would rather make sense to check the new name before setting
the instance variable, instead of resetting it after the caller
changed it in some obscure place. Here’s what I would have done:

def check name
some_condition or raise “I have probems with being named
#{new_name}.”
end
private :check

def name= new_name
check new_name
@name = new_name
end

def transactionally tmp_name
check tmp_name
old_name, @name = @name, tmp_name
begin
yield
ensure
@name = old_name
end
end

Everything untested.

Bertram