views:

135

answers:

1

I don't understand class_eval in ruby.

class Module
  def attr_ (*syms)
    syms.each do |sym|
      class_eval %{def #{sym}= (val)
        @#{sym} end} = val
    end
  end
end

What does the % mean?

What does class_eval do?

And where is (val) coming from?

Thanks

+4  A: 

The %{hello} is just another way to write a string literal in Ruby, without having to worry about escaping double or single quotes within the string:

%{hello "world"} == "hello \"world\""  # => true

The val in your code is and argument of the method being defined.

The class_eval is used to define some methods by computing the text one would write to do the definition and then evaluating it. It is not necessary here, BTW. An equivalent code would be:

class Module
  def attr_ (*syms)
    syms.each do |sym|
      define_method "#{sym}=" do |val|
        instance_variable_set "@#{sym}", val
      end
    end
  end
end

This is just equivalent to the builtin attr_writer.

Marc-André Lafortune
what does the word evaluate mean? i dont get that word.
never_had_a_name
In this context, execute some instructions.If you were to "evaluate" the expression 6 + 5, it's 11.