[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Means of Optional Expression

Trans

6/18/2007 5:49:00 PM

Have a look at this. Note that I'm not bothering to implement the
#shuffle method as it is not the point --it's just an foo example.

module Kernel
def express(name)
extend self.class.const_get(name.to_s.capitalize)
end
end

class Array
module Random
def shuffle
[] # ...
end

def shuffle!
replace(shuffle)
end

# ...
end
end

a = [1,2,3]
a.shuffle #=> NoMethodError

a.express(:Random)
a.shuffle #=> []

T.


3 Answers

Trans

6/18/2007 7:46:00 PM

0


On Jun 18, 1:48 pm, Trans <transf...@gmail.com> wrote:
>
> module Kernel
> def express(name)
> extend self.class.const_get(name.to_s.capitalize)
> end
> end
>
> class Array
> module Random
> def shuffle
> [] # ...
> end
>
> def shuffle!
> replace(shuffle)
> end
>
> # ...
> end
> end
>
> a = [1,2,3]
> a.shuffle #=> NoMethodError
>
> a.express(:Random)
> a.shuffle #=> []

FYI. I'm thinking about using this approach for Facets' Core
extensions in 2.0. There would be two versions of each require, one
that automatically includes the extension and one that does not.

T.


Todd Benson

6/18/2007 10:21:00 PM

0

On 6/18/07, Logan Capaldo <logancapaldo@gmail.com> wrote:
> I don't see it being worth it really. a.extend(Array::Random); a.shuffle
> What is this buying you? (Besides 6 characters, anyway)

I like it. Does anybody see a potential problem for this unobtrusive
'opening' of the class?

Todd

Trans

6/19/2007 3:40:00 AM

0



On Jun 18, 4:31 pm, "Logan Capaldo" <logancapa...@gmail.com> wrote:

> I don't see it being worth it really. a.extend(Array::Random); a.shuffle
> What is this buying you? (Besides 6 characters, anyway)

Besides being more concise, it also limits us to valid choices. Of
course we can always use extend, but a.extend(String::Random) would
more than likely make a mess of things, and might not even die early
causing peculiar hard to track bugs.

T.