Forum: Ruby More Proc Beauty

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
5da4c52f43677f395aff5bde775593c2?d=identicon&s=25 Daniel Schierbeck (dasch)
on 2006-05-08 13:47
(Received via mailing list)
The madness continues! This is getting out of hand!

First, a recap:

   class Symbol
     def to_proc
       # leave out the `&block' unless
       # you're using Ruby 1.9
       proc{|obj, *args, &block| obj.send(self, *args, &block) }
     end
   end

   # now we can do stuff like this:
   %w{dog cat monkey}.collect(&:upcase) => ["DOG", "CAT", "MONKEY"]

   # this is also mainly 1.9 stuff
   module Enumerable
     class Enumerator
       def &(name)
         each(&name)
       end
     end
   end

   # This is cool, but it looks kind of weird:
   %w{cat dog monkey}.collect&:reverse => ["tac", "god", "yeknom"]

And here's the new stuff:

   # now, this is really, really stupid in a real-world app.
   # but hey, it's still pretty cool!
   def method_missing(name, *args)
     return name
   end

   # now just look at all the coolness!
   %w{dog cat monkey}.collect&upcase => ["DOG", "CAT", "MONKEY"]

   # You can even put spaces in!
   %w{dog cat monkey}.collect & reverse =>  ["tac", "god", "yeknom"]

   # this will of course break if the variable is defined
   upcase = "foobar"
   %w{dog cat monkey}.collect & upcase => TypeError

I can't believe I used to write in PHP!


Cheers,
Daniel
4674615d2cf231975c741731be9a8685?d=identicon&s=25 why the lucky stiff (Guest)
on 2006-05-08 19:09
(Received via mailing list)
Daniel Schierbeck wrote:
> The madness continues! This is getting out of hand!
Scarlet fever.  Tell me, is there a little red ping-pong ball floating
in your peripheral vision that you can't ever seem to stare directly
at?  In time, it will become your dearest friend.
>   # now, this is really, really stupid in a real-world app.
>   # but hey, it's still pretty cool!
>   def method_missing(name, *args)
>     return name
>   end
>
>   # now just look at all the coolness!
>   %w{dog cat monkey}.collect&upcase => ["DOG", "CAT", "MONKEY"]
Or maybe you could move your method_missing into Enumerator.  Then you
could do:

  %w{dog cat monkey}.collect.upcase => ["DOG", "CAT", "MONKEY"]

_why
5da4c52f43677f395aff5bde775593c2?d=identicon&s=25 Daniel Schierbeck (dasch)
on 2006-05-08 19:52
(Received via mailing list)
why the lucky stiff wrote:
> Or maybe you could move your method_missing into Enumerator.  Then you
> could do:
>
>  %w{dog cat monkey}.collect.upcase => ["DOG", "CAT", "MONKEY"]

Suuuure, if you want to do it the _easy_ way! :P

Hehe, I was merely mesmerized by how easy it was to implement something
like that.


Cheers,
Daniel
This topic is locked and can not be replied to.