method
instance_eval
Ruby latest stable (v2_5_5)
-
1 note -
Class: Object
- 1_8_6_287 (0)
- 1_8_7_72 (0)
- 1_8_7_330 (0)
- 1_9_1_378
- 1_9_2_180
- 1_9_3_125
- 1_9_3_392
- 2_1_10
- 2_2_9
- 2_4_6
- 2_5_5
- 2_6_3
- What's this?
instance_eval(...)
public
Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.
class Klass def initialize @secret = 99 end end k = Klass.new k.instance_eval { @secret } #=> 99
Register or
log in
to add new notes.
sselvamani22 -
August 18, 2015
0 thanks
Add method to instacne eval
We can add method to instance by using instance_eval.
Code example
string = "String" string.instance_eval do def new_method self.reverse end end
Output
irb(main):033:0> string.new_method => "gnirtS"