Solving strings and blocks in Ruby

Source: Internet
Author: User

Introduced

The string and block solver that contains the code is one of my favorite Ruby features. Ruby offers a variety of different types of solutions, but what I use most is the following: eval, Instance_eval, and Class_eval.

Module.class_eval

Using the Class_eval (and its alias Module_eval) method of the module class, you can solve a given string or block in the definition of a class or in the context of a module definition. We often use Class_eval to add methods to the definition of a class, or to include other module.

klass = Class.new
klass.class_eval do
include ERB::Util
def encoded_hello
htnl_escape "Hello World"
end
end
klass.new.encoded_hello #=> Hello World

The above effect can be achieved without using class_eval, but the readability of the code is sacrificed.

klass = Class.new
klass.send :include, ERB::Util
klass.send :define_method, :encoded_hello do
html_escape "Hello World"
end
klass.send :public, :encoded_hello
klass.new.encoded_hello #=> Hello World

Object.instance_eval

Using the Instance_eval method of object, you can solve a given string or block in the context of a class instance. This is a powerful concept: You can create a piece of code in any context first, and then solve the code in the context of a separate object instance. To set the context in which the code executes, the self variable is set to the object instance where the code executes, so that the code can access the variables of the object instance.

class Navigator
def initialize
@page_index = 0
end
def next
@page_index += 1
end
end
navigator = Navigator.new
navigator.next
navigator.next
navigator.instance_eval "@page_index" #=> 2
navigator.instance_eval { @page_index } #=> 2

Like the example of using Class_eval, the value of an instance variable can be obtained in other ways, but using instance_eval is a very intuitive practice.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.