The Ruby 2 metaprogramming example from the book doesn't work when I try. Troubleshooting help

After reading the Metaprogramming Ruby 2 chapter, I came across an example in the book that doesn't seem to work when I execute the code.

array_explorer.rb

def explore_array(method)
  code = "['a','b','c'].#{method}"
  puts "Evaluating: #{code}"
  eval code
end

loop { p explore_array(gets()) }

      

The code above is intended to illustrate the power of eval. In the following example, the book teaches the main disadvantage of code injection and refactoring such code to protect:

array_explorer.rb

def explore_array(method, *arguments)
  ['a','b','c'].send(method, *arguments)
end

loop { p explore_array(gets()) }

      

When I try to run the above code, the file always gives me this error no matter which array method I am trying to place.

array_explorer.rb:2:in `explore_array': undefined method `:size (NoMethodError)
' for ["a", "b", "c"]:Array

      

I tried to take out a piece *arguments

to destroy it. I've tried using a string as input, character as input, etc. This code doesn't work for some reason. Does anyone know why?

+3


source to share


1 answer


gets

reads a line from STDIN

; "string" is defined as a string of characters terminated with a newline character ( \n

). Thus, you are trying to call a method "size\n"

that doesn't exist. Use chomp

to get rid of the newline:

loop { p explore_array(gets.chomp) }

      



In the first example, it doesn't matter since you are evaluating code "['a', 'b', 'c'].size\n"

that is still valid.

+3


source







All Articles