覆盖“for” Ruby 中的关键字。是否可以?

发布于 2024-08-13 04:16:39 字数 192 浏览 4 评论 0原文

我四处搜索并尝试覆盖“for”关键字,但我什么也没找到。 我正在尝试类似的事情:

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

for i in 1..3
  print "Hello from for"
end 

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 in 1..3
  print "Hello from for"
end 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

北方的巷 2024-08-20 04:16:39

您不能覆盖关键字本身,但您可以做的一件事是说明 for 对您自己的类执行的操作。 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

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
寂寞笑我太脆弱 2024-08-20 04:16:39

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

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

loop 1..6 do |x|
  #do something with 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
独守阴晴ぅ圆缺 2024-08-20 04:16:39

如果你给这个方法一个显式的接收者,它会起作用,但是如果你没有显式地将 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

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

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!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文