开发者

Overriding the "for" keyword in Ruby. Is it possible?

开发者 https://www.devze.com 2022-12-13 18:56 出处:网络
I search around and tried overriding the \"for\" keyword but I found nothing. I am trying something like that:

I search around and tried overriding the "for" keyword but I found nothing. I am trying something like that:

def for("maybe_arguments_go_here")
  print "Hello from function for!"
end

for i 开发者_StackOverflowin 1..3
  print "Hello from for"
end 


You can't override the keyword itself, but one thing you can do is say what for does for your own classes. for calls each internally, so the following trick will work:

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


I don't think that 'overriding' a keyword is an option at any language, you can override methods and operators(operators themselves are methods in modern languages) only, for is a keyword in Ruby. However you still can do things like the following:

def loop(range)
  range.each{|i| yield i}
end

loop 1..6 do |x|
  #do something with x
end


If you give the method an explicit receiver it would work, but you would not be able to use the method without explicitly putting self before it.

This would work:

def self.for(arg)
  arg + 1
end

self.for(1)
=> 2

OR

 class Aa
   def c
    self.for(1)
   end

   def for(arg)
     arg + 1
   end
 end

 b = Aa.new
 b.for(4)
 => 5

BUT, I agree with khell and some of the comments above that redefining keywords is a massive no no, of course, if we're just experimenting and having fun, then go for it!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号