Robert Klemme
5/17/2007 10:48:00 AM
On 17.05.2007 07:09, aurelianito wrote:
>
> On 17 mayo, 01:33, Peña, Botp <b...@delmonte-phil.com> wrote:
>> # irb(main):005:0> greeting="hi, #{"Ms "+name.capitalize}"
>> # => "hi, Ms Aure"
>>
>> sorry, was too fast on the last example; should be..
>>
>> irb(main):006:0> greeting="hi, #{name="Anne";"Ms "+name.capitalize}"
>> => "hi, Ms Anne"
>
> I'm trying to do some metaprogramming and I need to apply some
> operation to all the strings that are interpolated. But I can't change
> the interpolation. In the example, I would like that "hi, #{name}" to
> evaluate to "hi, AURE" instead of "hi, Aure". I know that inside the
> #{} "operator" I can put any ruby code, so "hi, #{name.capitalize}"
> would evaluate to what I want.
>
> But I want it to execute code that I DON'T write there. Ideally, there
> should be a method hook or something to change the way the
> interpolation works. But I couldn't find it :(. May be a different
> example may be more clear. How can I do to write to a file all the
> strings generated via interpolations (id est, all the strings that are
> generated evaluating the different #{} "operators" in a program)?
Frankly, it has not become clear to me what you are up to. Can you
maybe just state which problem you are trying to solve?
As for a solution to your original example, you can do something like
this - but it's a hack and not very reliable:
class Env
def initialize(vals)
@vals = vals
end
def process(&b)
instance_eval(&b)
end
def method_missing(s,*a,&b)
super unless a.empty?
@vals[s.to_sym].upcase
end
end
irb(main):015:0> e=Env.new(:name=>'foo')
=> #<Env:0x7ff6d388 @vals={:name=>"foo"}>
irb(main):016:0> e.process { "bar #{name}" }
=> "bar FOO"
irb(main):017:0>
Kind regards
robert