代码之家  ›  专栏  ›  技术社区  ›  Jon Romero

重写Ruby中的“for”关键字。有可能吗?

  •  1
  • Jon Romero  · 技术社区  · 15 年前

    我四处搜索,试图覆盖“for”关键字,但什么也没找到。 我正在尝试这样的方法:

    def for("maybe_arguments_go_here")
      print "Hello from function for!"
    end
    
    for i in 1..3
      print "Hello from for"
    end 
    
    3 回复  |  直到 15 年前
        1
  •  6
  •   Martin DeMello    15 年前

    您不能重写关键字本身,但您可以做的一件事是说什么 for 是为你自己的课做的。 对于 电话 each 在内部,以下技巧将起作用:

    class MyFor
      def initialize(iterable)
        @iterable = iterable
      end
    
      def each
        @iterable.each do |x|
          puts "hello from for!"
          yield x
        end
      end
    end
    
    # convenient constructor
    module Kernel
      def my(x)
        MyFor.new(x)
      end
    end
    
    for i in my(1..3)
      puts "my for yielded #{x}"
    end
    
        2
  •  3
  •   khelll    15 年前

    我不认为在任何语言中“重写”关键字都是选项,您只能重写方法和运算符(运算符本身是现代语言中的方法)。 for 是Ruby中的关键字。但是,您仍然可以执行以下操作:

    def loop(range)
      range.each{|i| yield i}
    end
    
    loop 1..6 do |x|
      #do something with x
    end
    
        3
  •  1
  •   btelles    15 年前

    如果您给方法一个显式接收器,它将工作,但如果不显式地将self放在方法之前,您将无法使用该方法。

    这是可行的:

    def self.for(arg)
      arg + 1
    end
    
    self.for(1)
    => 2
    

     class Aa
       def c
        self.for(1)
       end
    
       def for(arg)
         arg + 1
       end
     end
    
     b = Aa.new
     b.for(4)
     => 5
    

    但是,我同意凯尔和上面的一些评论,重新定义关键词是一个巨大的不,当然,如果我们只是在尝试和享受乐趣,那么就去做吧!

    推荐文章