views:

650

answers:

2

Hi, I have a quick question in Ruby

Lets say I ask the user to enter a name ( for a new class that i want to create)

my code is:

puts "enter the name for a new class that you want to create"
nameofclass = gets.chomp
nameofclass = Class.new

Why does this not work?

Also, I want to ask the user to enter the name of a method that i want to add to that class

my code is:

puts "enter the name for a new method that you want to add to that class"
nameofmethod = gets.chomp

nameofclass.class_eval do
    def nameofmethod
      p "whatever"
    end
end

This does not work either

-Can anyone help me please, Thank you

+3  A: 

The following code:

nameofclass = gets.chomp
nameofclass = Class.new

Is interpreted by the machine as:

Call the function "gets.chomp"
Assign the output of this call to a new variable, named "nameofclass"
Call the function "Class.new"
Assign the output of this call to the variable "nameofclass"

As you can see, if you follow the above, there is one variable, which gets assigned to twice. When the second assignment happens, the first is lost.

What you're trying to do, is presumably to create a new class and name it the same as the result of gets.chomp. To do this, you could use eval:

nameofclass = gets.chomp
code = "#{nameofclass} = Class.new"
eval code

There are other ways too, this being Ruby, but eval is probably the easiest to understand.

troelskn
thanks , you helped me out alot
+1 for clear explanation / -1 for recommending `eval`.
rampion
I should note that I agree that `eval` is nasty to see in production code. However, this seems like a very experimental case in the first place; You wouldn't ever want to do something like this. The benefit of `eval` is that it's easy to understand for a beginner, and it works fine as an introduction to meta-programming.
troelskn
+3  A: 

I like troelskn's answer for its explanation of what's happening quit a bit.

To avoid using the very dangerous eval, try this:

Object.const_set nameofclass, Class.new
James A. Rosen