From: Josh Cheek Date: 2010-06-03T01:18:31+09:00 Subject: Re: having a class method called only one time ? --0016e659fd8ea568f204880e70c2 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable 2010/6/2 Une B=E9vue > I'd like having a class method called only one time ? > Is it possible ? > > suppose i do have a class "HFSFile" and i need to know the host ip. > > i don't want to call the method giving host ip each time i need it but > only the first time even i do instantiate several HFSFile, mostly > because it's time consuming : > > @h[:host_ip] =3D `curl -s http://whatismyip.org`.chomp > > it is even in a while loop because sometimes curl returns ''. > > > -- > =AB Les faiblesses des hommes font la force des femmes. =BB > (Voltaire) > > This is basically the same as what other people have said, but uses begin ... end to do the entire calculation in one method. Also, addresses that it should only calculate once, across all instances. class HFSFile # assumes all instances of this class have the same host_ip # frozen just b/c a lot of objects are going to be using it def self.host_ip @@host_ip ||=3D begin puts "calculating host_ip" ip =3D `curl -s http://whatismyip.org`.chomp until ip && !ip.empty? ip.freeze end end # instance forwards to class # if there is a better way to do this, someone let me know def host_ip self.class.host_ip end end hfs1 =3D HFSFile.new puts hfs1.host_ip puts hfs1.host_ip hfs2 =3D HFSFile.new puts hfs2.host_ip puts hfs2.host_ip ----- Also, the delightful Ruby Best Practices discusses lazy evaluation in chapter 5. You can download a copy at http://rubybestpractices.com/ and if you feel you got something worthwhile, you might consider purchasing it as well :) ----- And depending on where you are going with this, you could also consider rake, which is built around tasks and dependencies, and won't execute a tas= k more than one time (per user invocation). --0016e659fd8ea568f204880e70c2--