From: Sy Ali Date: 2006-09-11T02:57:45+09:00 Subject: Re: patching strings together to make a variable On 9/10/06, Mike Stok wrote: > > Previously, I've been duplicating methods and just renaming a single > > variable.. (just to ensure that method1 works the same as method2) a > > variation of this would be cleaner I think. > > > > My code is still quite hackish, so it's likely that I'll figure things > > out in some time, and will be able to evolve towards even cleaner > > code, perhaps dropping this trick. > > What are you actually trying to do? Sometimes stepping back from a > particular obstacle can give a fresh point of view which sometimes > leads to "nicer" code. > > Mention of duplicating methods and renaming a single variable hints > strongly there may be more ways to skin this cat. I was just looking for an alternative to the classic if/then/else. My original method would do this: def test1 puts "#{@something_something}" end def test2 puts "#{@something_something_else}" end or maybe I could have done this: def test(string) if string == "something" then puts "#{@something_something}" elsif string == "something_else" then puts "#{@something_something_else}" end end What if I wanted to expand this a thousand-fold? I'd have to do this: def test(string) case string when "something" : puts "#{@something_something}" when "something_else" : puts "#{@something_something_else}" # ... repeated many more times end end But that thousand-line case could be replaced with a one-liner: def test(string) puts "#{instance_variable_get("@#{string + "_something"}")}" end I got here because I was looking at my inelegant code and wanted to know how it could be simplified when faced with greater use. Thinking in infinites.. yes, it's optimising early, but I wanted to learn something new.