[Q] little regexp challenge

H

henon

hi,

i want to do the following:

replace the occurrances of an access of a hash (namely widgets) by an
access to a instance variable in a piece of ruby code:

example:
"
widgets['button1'].text='hello'
widgets['textfield2'].text='hi'
aHash['aString']='aValue'
aHash['annother']='aValue'
"

should be replaced by

"
@button1.text='hello'
@textfield2.text='hi'
aHash['aString']='aValue'
aHash['annother']='aValue'
"

using gsub.

could you guys give me a hint how to do this?

thanks,
-- henon
 
P

Peter C. Verhage

henon said:
could you guys give me a hint how to do this?

Something like this? (Haven't tested it, though):

gsub("widgets\['([a-z]+)'\]", "@\1") or something like that?

Regards,

Peter
 
H

henon

Peter said:
henon said:
could you guys give me a hint how to do this?


Something like this? (Haven't tested it, though):

gsub("widgets\['([a-z]+)'\]", "@\1") or something like that?

Regards,

Peter
thanks,

btw: what would be substituted for \0?

- henon
 
F

Florian Groß

henon said:
hi,
Moin!

replace the occurrances of an access of a hash (namely widgets) by an
access to a instance variable in a piece of ruby code: [...]

This is a solution which doesn't change the code -- instead it
implements a simple wrapper which lets you access instance variables
through the [] and []= methods. This might not be exactly what you
wanted, but it was interesting to code anyway! :)

class Widget
def [](key)
instance_variable_get("@" + key)
end

def []=(key, value)
instance_variable_set("@" + key, value)
end
end

irb(main):001:0> x = Widget.new; x['foo'] = 1
=> 1
irb(main):002:0> x['foo'] += 1
=> 2

Regards,
Florian Gross
 
R

Robert Klemme

Florian Groß said:
henon said:
hi,
Moin!

replace the occurrances of an access of a hash (namely widgets) by an
access to a instance variable in a piece of ruby code: [...]

This is a solution which doesn't change the code -- instead it
implements a simple wrapper which lets you access instance variables
through the [] and []= methods. This might not be exactly what you
wanted, but it was interesting to code anyway! :)

class Widget
def [](key)
instance_variable_get("@" + key)
end

def []=(key, value)
instance_variable_set("@" + key, value)
end
end

irb(main):001:0> x = Widget.new; x['foo'] = 1
=> 1
irb(main):002:0> x['foo'] += 1
=> 2

Regards,
Florian Gross

Hehe, nice cheating. :)))

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top