SlideShare une entreprise Scribd logo
1  sur  12
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 !

Contenu connexe

Tendances

ملخص الفيزياء السادس العلمي - سعيد محي تومان
ملخص الفيزياء السادس العلمي - سعيد محي تومانملخص الفيزياء السادس العلمي - سعيد محي تومان
ملخص الفيزياء السادس العلمي - سعيد محي تومانOnline
 
Equilibre acide base esf
Equilibre acide base esfEquilibre acide base esf
Equilibre acide base esfesf3
 
Les monuments de la France
Les monuments de la FranceLes monuments de la France
Les monuments de la FranceAna Miras
 
Base ECG et l'interprétation du rythme (French) Symposia
Base ECG et l'interprétation du rythme (French) SymposiaBase ECG et l'interprétation du rythme (French) Symposia
Base ECG et l'interprétation du rythme (French) SymposiaThe CRUDEM Foundation
 
Médicaments de l’hypertension artérielle
Médicaments de l’hypertension artérielleMédicaments de l’hypertension artérielle
Médicaments de l’hypertension artérielleEmna Jaoued
 

Tendances (8)

Quizz ecg n°1
Quizz ecg n°1Quizz ecg n°1
Quizz ecg n°1
 
ملخص الفيزياء السادس العلمي - سعيد محي تومان
ملخص الفيزياء السادس العلمي - سعيد محي تومانملخص الفيزياء السادس العلمي - سعيد محي تومان
ملخص الفيزياء السادس العلمي - سعيد محي تومان
 
Equilibre acide base esf
Equilibre acide base esfEquilibre acide base esf
Equilibre acide base esf
 
Les monuments de la France
Les monuments de la FranceLes monuments de la France
Les monuments de la France
 
Base ECG et l'interprétation du rythme (French) Symposia
Base ECG et l'interprétation du rythme (French) SymposiaBase ECG et l'interprétation du rythme (French) Symposia
Base ECG et l'interprétation du rythme (French) Symposia
 
Crises convulsives
Crises convulsivesCrises convulsives
Crises convulsives
 
Médicaments de l’hypertension artérielle
Médicaments de l’hypertension artérielleMédicaments de l’hypertension artérielle
Médicaments de l’hypertension artérielle
 
Douleurs thoraciques
Douleurs thoraciques Douleurs thoraciques
Douleurs thoraciques
 

Similaire à Introduction to ruby eval

Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in RubyConFoo
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogrammingjoshbuddy
 
Selfish presentation - ruby internals
Selfish presentation - ruby internalsSelfish presentation - ruby internals
Selfish presentation - ruby internalsWojciech Widenka
 
Runtime Tools
Runtime ToolsRuntime Tools
Runtime ToolsESUG
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APINiranjan Sarade
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0tutorialsruby
 
Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyTushar Pal
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیMohammad Reza Kamalifard
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAMaulik Borsaniya
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objectsHarkamal Singh
 

Similaire à Introduction to ruby eval (20)

Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Specs2
Specs2Specs2
Specs2
 
Selfish presentation - ruby internals
Selfish presentation - ruby internalsSelfish presentation - ruby internals
Selfish presentation - ruby internals
 
Runtime Tools
Runtime ToolsRuntime Tools
Runtime Tools
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0RubyMiniGuide-v1.0_0
RubyMiniGuide-v1.0_0
 
Python advance
Python advancePython advance
Python advance
 
About Python
About PythonAbout Python
About Python
 
Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for ruby
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
Scala
ScalaScala
Scala
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Lab 4
Lab 4Lab 4
Lab 4
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 

Dernier

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Dernier (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

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