Overwriting "if"

Discussion in 'Ruby' started by Matthew Rudy, Jul 19, 2007.

  1. Matthew Rudy

    Matthew Rudy Guest

    I want to overwrite if,
    but it doesn't seem to work.

    module Kernel
    def if(arg)
    yield
    end
    end

    def if(arg)
    yield
    end

    doesn't seem to work.
    I know I could define my own if,
    but it seems like ruby, being so dynamic, should be capable of this.

    Any amusing suggestions on how to implement this will be much welcomed.

    MatthewRudy
     
    Matthew Rudy, Jul 19, 2007
    #1
    1. Advertisements

  2. Be like Smalltalk!

    irb> class Object
    irb> def if
    irb> if self
    irb> yield
    irb> end
    irb> end
    irb> end
    => nil

    irb> (4==4).if { p :true }
    :true
    => nil
    irb> (4==6).if { p :true }
    => nil

    irb> class Object
    irb> def if(blocks)
    irb> if self
    irb> blocks[:then].call
    irb> else
    irb* blocks[:else].call
    irb> end
    irb> end
    irb> end
    => nil

    irb> (4==4).if :then => lambda { p :true }, :else => lambda { p :false }
    :true
    => nil
    irb> (4==6).if :then => lambda { p :true }, :else => lambda { p :false }
    :false
    => nil
    irb>


    Be like Arc!!

    irb> alias fn lambda
    => nil
    irb> (4==6).if :then => fn { p :true }, :else => fn { p :false }
    :false
    => nil
     
    Daniel Lucraft, Jul 19, 2007
    #2
    1. Advertisements

  3. Matthew Rudy

    Matthew Rudy Guest

    that's cool,
    but can we not redefine the default "if"
    so that the following code will work

    if false
    return "false is true"
    end

    without resorting to calling a method on a class / instance / module
    explicitly

    I'm thinking that intead we can overwrite the evaluation of False and
    NilClass
    ?


     
    Matthew Rudy, Jul 19, 2007
    #3
  4. I want to overwrite if,
    Of course this is something we really need in Ruby ;-)

    This reminds me on the following, valid (and at its time popular),=20
    PL/1 code:

    IF IF=3DTHEN
    THEN THEN=3DELSE
    ELSE ELSE=3DIF;

    Ronald
    --=20
    Ronald Fischer <>
    Phone: +49-89-452133-162
     
    Ronald Fischer, Jul 19, 2007
    #4
  5. Don't think so: 'if' is a keyword. You'll never get it to look for a
    method called 'if' without rewriting the interpreter.
    Is there a reason for all this or are you just amusing yourself? :)

    Dan
     
    Daniel Lucraft, Jul 19, 2007
    #5
  6. Matthew Rudy

    Matthew Rudy Guest

    just for fun
    :)

    if only keywords could be overwritten.
    I guess I could just rebuild the parser.

    anyway,
    thanks for your suggestions,
    back to work

    Mj
     
    Matthew Rudy, Jul 19, 2007
    #6
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.