SlideShare a Scribd company logo
topic = ‘Introduction to Ruby eval’
           eval(“p topic”)
                          - Niranjan Sarade
Binding and eval

If ruby program can generate a string of valid ruby code, the Kernel.eval
method can evaluate the code.

A Binding object represents the state of Ruby’s variable bindings at some
moment.

The Kernel.binding (private method) returns the bindings in effect at the
location of the call.

Binding object is second argument to eval and the string you specify will be
evaluated in the context of those bindings.
eval

eval only takes a string to evaluate. eval will evaluate the string in the current
context or if a binding is given.

def getBinding(str)    # returns the current context of the value of str
    return binding
end

str = "hello"

eval "str + ' Fred'" #=> "hello Fred"

eval "str + ' Fred'", getBinding("bye") #=> "bye Fred"
If we define an instance method that returns a Binding object that represents
the variable bindings inside an object,

class Object
    def bindings
          binding
    end
end

class A
    def initialize(x)
           @x = x
    end
end

a = A.new(5)
eval(“@x”, a.bindings) #=> 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
 end




A.hello_1 #=> undefined method `hello' for A:Class (NoMethodError)


A.new.hello_1 #=> “hello”
A.instance_eval do
 def hello_2
  p 'hello_2'
 end
end

A.hello_2 #=> "hello_2"

A.new.hello_2 #=> undefined method `hello_2' for #<A:0x32d05fc> (NoMethodError)
a = A.new
a.instance_eval do
 def hello_3
   p 'hello_3'
 end
end

a.hello_3 #=> "hello_3"

b = A.new
b.hello_3 #=> undefined method `hello_3' for #<A:0x32d019c> (NoMethodError)
instance_eval => Object class
module_eval (synonym for class_eval) => Module class

They evaluate the code in the context of the specified object, i.e. value of self
while code is being evaluated.

# Returns value of a’s instance variable @x
a.instance_eval(“@x”)

# Define an instance method len of String
String.class_eval(“def len; size; end”)

# The quoted code behaves just as if it was inside class String and end
String.class_eval("alias len size")


class_eval is a function that can ONLY be called by class as the name
suggests.
# Use instance_eval to define class method String.empty
String.instance_eval(“def empty; ‘ ’ ; end”)

instance_eval defines singleton methods of the object (& this results in class
method 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
    end
end

Ruby 1.9 :- instance_exec and class_exec
They can accept arguments as well and pass them to block
class A
  has_attribute :my_attribute, :another_attribute
end

a = A.new

puts a.methods - Object.methods
# => ["my_attribute", my_attribute=", "another_attribute", "another_attribute="]

a.my_attribute = 1
a.my_attribute # => 1

a.another_attribute = "A String"
a.another_attribute # => "A String"
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
 end
end
Thank you !

More Related Content

Similar to Introduction to ruby eval (20)

Ruby objects
Ruby objectsRuby objects
Ruby objects
Reuven Lerner
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
Nicolò Calcavecchia
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
Niranjan Sarade
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
Kushal Jangid
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
Giovanni924
 
CS169 UC Berkeley Armando Fox Ruby basics
CS169 UC Berkeley Armando Fox Ruby basicsCS169 UC Berkeley Armando Fox Ruby basics
CS169 UC Berkeley Armando Fox Ruby basics
AnshGanatra
 
4 Expressions and Operators
4  Expressions and Operators4  Expressions and Operators
4 Expressions and Operators
Deepak Hagadur Bheemaraju
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
Santiago Pastorino
 
block
blockblock
block
Ma Xuebin
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
NagaLakshmi_N
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
Gonçalo Silva
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
Diego Lemos
 
Runtime Tools
Runtime ToolsRuntime Tools
Runtime Tools
ESUG
 
Deciphering the Ruby Object Model
Deciphering the Ruby Object ModelDeciphering the Ruby Object Model
Deciphering the Ruby Object Model
Karthik Sirasanagandla
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
Wei Jen Lu
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview Questions
Sumanth krishna
 
Ruby Internals
Ruby InternalsRuby Internals
Ruby Internals
Burke Libbey
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
Wen-Tien Chang
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
Niranjan Sarade
 
Slides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammersSlides chapter3part1 ruby-forjavaprogrammers
Slides chapter3part1 ruby-forjavaprogrammers
Giovanni924
 
CS169 UC Berkeley Armando Fox Ruby basics
CS169 UC Berkeley Armando Fox Ruby basicsCS169 UC Berkeley Armando Fox Ruby basics
CS169 UC Berkeley Armando Fox Ruby basics
AnshGanatra
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
Gonçalo Silva
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
Diego Lemos
 
Runtime Tools
Runtime ToolsRuntime Tools
Runtime Tools
ESUG
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
Wei Jen Lu
 
Ruby Interview Questions
Ruby Interview QuestionsRuby Interview Questions
Ruby Interview Questions
Sumanth krishna
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
Wen-Tien Chang
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
tutorialsruby
 

Recently uploaded (20)

Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Grannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI ExperiencesGrannie’s Journey to Using Healthcare AI Experiences
Grannie’s Journey to Using Healthcare AI Experiences
Lauren Parr
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
AI Trends - Mary Meeker
AI Trends - Mary MeekerAI Trends - Mary Meeker
AI Trends - Mary Meeker
Razin Mustafiz
 
Droidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing HealthcareDroidal: AI Agents Revolutionizing Healthcare
Droidal: AI Agents Revolutionizing Healthcare
Droidal LLC
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Ad

Introduction to ruby eval

  • 1. topic = ‘Introduction to Ruby eval’ eval(“p topic”) - Niranjan Sarade
  • 2. Binding and eval If ruby program can generate a string of valid ruby code, the Kernel.eval method can evaluate the code. A Binding object represents the state of Ruby’s variable bindings at some moment. The Kernel.binding (private method) returns the bindings in effect at the location of the call. Binding object is second argument to eval and the string you specify will be evaluated in the context of those bindings.
  • 3. eval eval only takes a string to evaluate. eval will evaluate the string in the current context or if a binding is given. def getBinding(str) # returns the current context of the value of str return binding end str = "hello" eval "str + ' Fred'" #=> "hello Fred" eval "str + ' Fred'", getBinding("bye") #=> "bye Fred"
  • 4. If we define an instance method that returns a Binding object that represents the variable bindings inside an object, class Object def bindings binding end end class A def initialize(x) @x = x end end a = A.new(5) eval(“@x”, a.bindings) #=> 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 end A.hello_1 #=> undefined method `hello' for A:Class (NoMethodError) A.new.hello_1 #=> “hello”
  • 6. A.instance_eval do def hello_2 p 'hello_2' end end A.hello_2 #=> "hello_2" A.new.hello_2 #=> undefined method `hello_2' for #<A:0x32d05fc> (NoMethodError)
  • 7. a = A.new a.instance_eval do def hello_3 p 'hello_3' end end a.hello_3 #=> "hello_3" b = A.new b.hello_3 #=> undefined method `hello_3' for #<A:0x32d019c> (NoMethodError)
  • 8. instance_eval => Object class module_eval (synonym for class_eval) => Module class They evaluate the code in the context of the specified object, i.e. value of self while code is being evaluated. # Returns value of a’s instance variable @x a.instance_eval(“@x”) # Define an instance method len of String String.class_eval(“def len; size; end”) # The quoted code behaves just as if it was inside class String and end String.class_eval("alias len size") class_eval is a function that can ONLY be called by class as the name suggests.
  • 9. # Use instance_eval to define class method String.empty String.instance_eval(“def empty; ‘ ’ ; end”) instance_eval defines singleton methods of the object (& this results in class method 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 end end Ruby 1.9 :- instance_exec and class_exec They can accept arguments as well and pass them to block
  • 10. class A has_attribute :my_attribute, :another_attribute end a = A.new puts a.methods - Object.methods # => ["my_attribute", my_attribute=", "another_attribute", "another_attribute="] a.my_attribute = 1 a.my_attribute # => 1 a.another_attribute = "A String" a.another_attribute # => "A String"
  • 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 end end