Ge Bro wrote:
> Great, so with everyone's help this is what I ended up doing in the end:

You didn't learn your lessons very well.  Look up what the method to_s 
does.  Does calling to_s on a string do anything?  Experiment.

> 7stud, my classes are defined in their corresponding controllers - this 
> is a part of a Rails exercise

This isn't a Rails forum.

> I came across .constantize after searching for const_get as phrogz 
> suggested.

If you are discarding the ruby solutions that were proffered in favor of 
rails specific solutions, then why not just go to the rails forum?

In any case, if you look at the definition of the constantize method, it 
just calls the ruby method module_eval, and  module_eval seems to act 
like const_get in your situation, although module_eval can also do some 
other things.


> btw, i do have to admit that i have no clear idea of why eval() works 
> here and what it's actually supposed to do. 

You don't seem to understand the difference between a variable name and 
a string.   The most obvious difference is that a string has quotes 
around it.  Look at this example:

arr = [1, 2, 3, 4, 5, 6, 7]

puts 'arr'.length
puts arr.length

Can you guess what the output will be?  Run the code and see if you are 
correct.

Now try this:

puts 'arr'[0, 1]
puts arr[0, 1]

Those lines say get the elements starting at position 0 and stopping at 
position 1(which does  not include the stopping position).  Can you 
guess the output?

A string and a variable name are different animals.

The eval method says to treat a string as if it is ruby code.  If your 
string looks like this:

str = "num = 10; puts num"

and you eval() that string then ruby will treat the string as code and 
execute it.  Essentially, eval removes the quotes around a string and 
then treats what's left as code.  As a result, when you ask ruby to eval 
a string like:

"name"

that becomes:

name

and to ruby that looks like a variable name or a method call.  Try this 
program:

eval("name")

--output:---
r5test.rb:1: undefined local variable or method `name' for main:Object 
(NameError)

ruby can't find a variable named name nor a method named name, so ruby 
produces the error message.  Now try this:

def name
  puts 'Jon'
end

name

The output should be obvious.  Now using eval:

def name
  puts 'Jon'
end

eval("name")

Why is that useful?  Why not just use the previous example's code? 
Because sometimes you have a method name as a string, and you want to 
execute the method, e.g.:

puts "What method do you want to execute: "
input = gets
input = input.strip

def hi
  puts 'hello'
end

def bye
  puts 'goodbye'
end

eval(input)

--output:--
What method do you want to execute:
hi
hello

However, you should avoid using eval whenever possible.  First, it's 
slow.  Second, someone could enter a string that contains a command to 
erase your hard drive.  When you eval that string, poof!







-- 
Posted via http://www.ruby-forum.com/.