From: Josh Cheek Date: 2011-08-01T05:34:12+09:00 Subject: Re: A question on style... --90e6ba48856de55f9604a9636fda Content-Type: text/plain; charset=ISO-8859-1 On Sun, Jul 31, 2011 at 3:06 PM, Joseph Phillips < psynaptic_accelerator@yahoo.com> wrote: > Hi everyone, > > Long time developer here, new to Ruby. > > I have a simple, single file Ruby program that randomly chooses a response > to input text. I have a method to return the the array of responses, which I > call further into the file in my main routine. This is the method: > > def get_responses > [ > "Got it.", > "Interesting. I've made a note of that.", > "Noted.", > "Right.", > "I see.", > "As you say." > ] > end > > Is this conventional? Is there any benefit in late acquisition of this > array, or would it be normal to just assign it to a variable up front? > > I wouldn't have a problem doing it, though I usually start like `[ "Got it.",` Anyway, there are two nuances to doing it that way. Whether they are benefits or not depends on your program. 1) Every time you call that method, the array it returns and the string contents, are all new objects. This can be beneficial in that you can mutate the array and it doesn't matter. It can be a problem if you call it a billion times and use up a lot of memory on duplicate objects and processing power recreating existing objects. 2) The method is globally visible (assuming you're defining it at the top level, in main), whereas a local variable would only be visible within the same scope. It can be a benefit in that you may want to call it from other scopes, it may be a problem in that it is potentially possible (though highly highly unlikely) that making it visible everywhere could cause an error elsewhere in your program. --90e6ba48856de55f9604a9636fda--