yield self if block_given?

R

Ruby Newbee

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.
 
R

Ruby Newbee

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
 
B

Bertram Scharpf

Hi,

Am Freitag, 01. Jan 2010, 23:54:12 +0900 schrieb Ruby Newbee:
class AngstyNamedPerson
@@hated_names = %w(Leroy Sparkles Thaddius)

attr_reader :name
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
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".

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,185
Members
46,736
Latest member
AdolphBig6

Latest Threads

Top