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.
I think an equivalent way is to directly open the singleton class of a
(what extend is doing in your implementation).
Sure, but if you need it in several arrays, the module approach is cleaner.
And I’d say that even for one array is cleaner too :).
Not only that: I’d expect it to use less resources, too. Reason is
that there is just one definition of the method. Plus, it’s easier to
later change it for all Array instances if that should be needed.
Marc, we do not know what your method #rand does and which Ruby
version you are using, but since 1.9 there is Array#sample which might
be exactly what you are looking for.
One solution would be to create a module with the rand method, and
some_elements = [1,2,3,4,5]
(what extend is doing in your implementation).
Sure, but if you need it in several arrays, the module approach is cleaner.
And I’d say that even for one array is cleaner too :).
Agreed.
I just thought that maybe it was easier to understand the concept of a
singleton
class of an object in isolation “change only the behavior of this
instance,
not
of the class or of other instances of the class”, without adding the
difference
between Module include and extend into the example.