From: Peter Vandenabeele Date: 2011-10-26T23:28:06+09:00 Subject: Re: Modify only a .rb file, but not other .rb files, while still extending core classes? --0016369fa10aacf64004b0347681 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: quoted-printable 2011/10/26 Jes=C3=BAs Gabriel y Gal=C3=A1n > On Wed, Oct 26, 2011 at 4:04 PM, Marc Heiler > wrote: > > Given is a small .rb file. > > > > In that .rb file, class Array is modified and a convenience > > method is added. > > > > class Array > > > > def rand > > > > I want to limit this modification to only that specific > > .rb file though. > > > > When I use that .rb file in a larger project, I do not want > > the modification of class Array to leak out into other .rb > > files. Is there a way to limit the scope of the modification? > > > > Of course I can define a method simply and call that, but: > > > > array.rand > > > > Looks better to my eyes than: > > > > rand(array) > > > > So I would prefer to be able to do only the array.rand. > > One solution would be to create a module with the rand method, and > extend only the arrays you use in that .rb: > > # small.rb > > module Randomizable > def rand > # your implentation > end > end > > some_elements =3D [1,2,3,4,5] > some_elements.extend(Randomizable) > some_elements.rand > > All other arrays in the system will not be affected. > > Jesus. > I think an equivalent way is to directly open the singleton class of a (what extend is doing in your implementation). peterv@ASUS:~$ irb 001:0> a =3D [1,2,3,4,5] =3D> [1, 2, 3, 4, 5] 002:0> class << a 003:1> def rand 004:2> self.sort_by!{|e| Kernel.rand} # without the Kernel reference, infinite loop is created 005:2> end 006:1> end =3D> nil 007:0> a.rand =3D> [4, 1, 5, 3, 2] 008:0> b =3D [6,7,8,9,10] =3D> [6, 7, 8, 9, 10] 009:0> Array.methods.grep(/rand/) =3D> [] 010:0> a.methods.grep(/rand/) =3D> [:rand] 011:0> b.methods.grep(/rand/) =3D> [] HTH, Peter --0016369fa10aacf64004b0347681--