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


-- 
Bertram Scharpf
Stuttgart, Deutschland/Germany
*
Support `String#notempty?': <http://raa.ruby-lang.org/project/step>.