From: Brian Candler Date: 2010-04-11T03:06:06+09:00 Subject: Re: global variable in ruby Jesse Jurman wrote: >> $buffer = Array.new > > While global variables are really nice, most programmers try not to use > them, as they cause a lot of errors in the long end, dealing with other > programs or add-ons. I try not to use Global Variables in my programs, > but when I do need to, I name them so specifically, that they can not be > confused with another program's global variables. > > i.e. $program_name_buffer00 = Array.new If it's just that a number of methods want access to the same buffer, you probably want to put them in a class and use an instance variable. class PageParser attr_reader :buffer def initialize(buffer = []) @buffer = buffer end def get_citations_from_page(data, start_point, end_point) citations = get_substring_within_inclusive(data, start_point, end_point) u_arr = getURLsFromPage('http://www.xxxx.com/', citations) u_arr.each { |t| if (!beginsWith(t[1],'http://www.xxxx.com//gp/reader')) @buffer.push t[0]+'%%%'+t[1] end } end def get_substring_within_inclusive ... end end parser = PageParser.new parser.get_citations_from_page(...) p parser.buffer If you really want a single buffer which is global to the whole program, then I'd say an instance variable of a Class is the way to go, which avoids the global variable namespace problem. class PageParser @buffer = [] def self.buffer @buffer end end PageParser.buffer << "hello" PageParser.buffer << "world" p PageParser.buffer In the above code, @buffer is an instance variable of the Class object, not of instances of class PageParser (since class PageParser is itself an object) -- Posted via http://www.ruby-forum.com/.