|
|
|
|
||||||
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 |
|
Messages: n/a
Hébergeur: |
kendear wrote:
> i wonder in Ruby, is there a line method to do something like in C > > > print_val("Array[3] + 1") > > and get the printout of > > > Array[3] + 1 is 3.345 > Here you go: def print_val(str) puts "#{str} is #{eval(str)}" end This should do what you want. Be wary of side effects, though. For example, to display the value of "a += 3" requires evaluation, and that changes the value of "a" (and when you remove this debugging line, your program no longer works the way you expect). Have fun, Dan |
|
|
|
#2 |
|
Messages: n/a
Hébergeur: |
On Sep 15, 2007, at 7:11 AM, Dan Zwell wrote:
> Here you go: > def print_val(str) > puts "#{str} is #{eval(str)}" > end That didn't work for me. I had modify it like so: foo = [1, 2, 3, 4, 5] def print_val(str) puts "#{str} is #{eval(str, TOPLEVEL_BINDING)}" end print_val("foo[3] + 1") Regards, Morton |
|
|
|
#3 |
|
Messages: n/a
Hébergeur: |
Morton Goldberg wrote:
> On Sep 15, 2007, at 7:11 AM, Dan Zwell wrote: > >> Here you go: >> def print_val(str) >> puts "#{str} is #{eval(str)}" >> end > > That didn't work for me. I had modify it like so: > > foo = [1, 2, 3, 4, 5] > def print_val(str) > puts "#{str} is #{eval(str, TOPLEVEL_BINDING)}" > end > print_val("foo[3] + 1") > > Regards, Morton > > You're right, thanks. When I tested this, I used the first poster's variable name, "Array". So it worked for me, but only because I happened to use a name with global slope. Dan |
|
|
|
#4 |
|
Messages: n/a
Hébergeur: |
On Sep 15, 5:22 am, Morton Goldberg <m_goldb...@ameritech.net> wrote: > That didn't work for me. I had modify it like so: > > foo = [1, 2, 3, 4, 5] > def print_val(str) > puts "#{str} is #{eval(str, TOPLEVEL_BINDING)}" > end > print_val("foo[3] + 1") it works but then if print_val is called inside an instance method, then it won't work. |
|
![]() |
| Outils de la discussion | |
|
|