|
|
|
|
||||||
![]() |
|
|
LinkBack | Outils de la discussion |
|
|
#1 (permalink) |
|
Messages: n/a
Hébergeur: |
On Sep 15, 2007, at 1:51 AM, 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 All you need is something like: puts "myArray[3] + 1 is #{myArray[3] + 1} " String interpolation. Great stuff. Of course you have to create that array first to have something in it. You could also do: puts "myArray[3] + 1 is " + (myArray[3] + 1).to_s Lots of ways, but the first one is most succinct. Ruby is very flexible! You can even go from this into a DSL with words that evaluate to expressions. |
|
|
|
#2 (permalink) |
|
Messages: n/a
Hébergeur: |
On 15.09.2007 19:13, John Joyce wrote:
> > On Sep 15, 2007, at 1:51 AM, 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 def print_val(expr,b=binding) print( expr, " is ", eval(expr,b).inspect, "\n") end irb(main):026:0> a=%{foo bar baz} => "foo bar baz" irb(main):027:0> print_val "a[1]", binding a[1] is 111 => nil irb(main):028:0> print_val "a[1]" NameError: undefined local variable or method `a' for main:Object from (irb):21:in `print_val' from (irb):21:in `print_val' from (irb):28 from :0 You can even omit the "b" argument if you use something like "Binding.of_caller". Kind regards robert |
|
![]() |
| Outils de la discussion | |
|
|