Introduction to ruby eval


Published on

This presentation is an introduction to Ruby eval. It also talks about instance_eval and class_eval methods and lists a meta programming example using eval at the end of the presentation.

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Introduction to ruby eval

  1. 1. topic = ‘Introduction to Ruby eval’ eval(“p topic”) - Niranjan Sarade
  2. 2. Binding and evalIf ruby program can generate a string of valid ruby code, the Kernel.evalmethod can evaluate the code.A Binding object represents the state of Ruby’s variable bindings at somemoment.The Kernel.binding (private method) returns the bindings in effect at thelocation of the call.Binding object is second argument to eval and the string you specify will beevaluated in the context of those bindings.
  3. 3. evaleval only takes a string to evaluate. eval will evaluate the string in the currentcontext or if a binding is given.def getBinding(str) # returns the current context of the value of str return bindingendstr = "hello"eval "str + Fred" #=> "hello Fred"eval "str + Fred", getBinding("bye") #=> "bye Fred"
  4. 4. If we define an instance method that returns a Binding object that representsthe variable bindings inside an object,class Object def bindings binding endendclass A def initialize(x) @x = x endenda =“@x”, a.bindings) #=> 5
  5. 5. class_eval and instance_eval class A; end class A A.class_eval do def hello_1 def hello_1 p ‘hello_1’ p hello_1 end end end endA.hello_1 #=> undefined method `hello for A:Class (NoMethodError) #=> “hello”
  6. 6. A.instance_eval do def hello_2 p hello_2 endendA.hello_2 #=> "hello_2" #=> undefined method `hello_2 for #<A:0x32d05fc> (NoMethodError)
  7. 7. a = A.newa.instance_eval do def hello_3 p hello_3 endenda.hello_3 #=> "hello_3"b = A.newb.hello_3 #=> undefined method `hello_3 for #<A:0x32d019c> (NoMethodError)
  8. 8. instance_eval => Object classmodule_eval (synonym for class_eval) => Module classThey evaluate the code in the context of the specified object, i.e. value of selfwhile code is being evaluated.# Returns value of a’s instance variable @xa.instance_eval(“@x”)# Define an instance method len of StringString.class_eval(“def len; size; end”)# The quoted code behaves just as if it was inside class String and endString.class_eval("alias len size")class_eval is a function that can ONLY be called by class as the namesuggests.
  9. 9. # Use instance_eval to define class method String.emptyString.instance_eval(“def empty; ‘ ’ ; end”)instance_eval defines singleton methods of the object (& this results in classmethod when it is called on a class object)class_eval defines regular instance methods.They can accept a block of code to evaluate. Eval can not.a.instance_eval {@x}String.class_eval { def len size endendRuby 1.9 :- instance_exec and class_execThey can accept arguments as well and pass them to block
  10. 10. class A has_attribute :my_attribute, :another_attributeenda = A.newputs a.methods - Object.methods# => ["my_attribute", my_attribute=", "another_attribute", "another_attribute="]a.my_attribute = 1a.my_attribute # => 1a.another_attribute = "A String"a.another_attribute # => "A String"
  11. 11. Object.instance_eval do def has_attribute( *attrs ) attrs.each do | attr | self.class_eval %Q{ def #{attr}=(val) instance_variable_set("@#{attr}", val) end def #{attr} instance_variable_get("@#{attr}") end } end endend
  12. 12. Thank you !
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.