gpt4 book ai didi

ruby - 如何在main中动态创建局部变量

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:25 24 4
gpt4 key购买 nike

如何在普通 ruby​​ 文件的主绑定(bind)中定义变量?

我已经尝试过 TOPLEVEL_BINDING,但它不会将变量共享到主作用域

#!/usr/bin/env ruby
# ....

5.times do |i|
src = %(
reader#{i} = library.create_reader "name"
book#{i} = library.create_book "title"
)
TOPLEVEL_BINDING.eval(src)
end

3.times { reader0.take(book0) } # error
5.times { reader1.take(book1) }
1.times { reader2.take(book2) }
0.times { reader3.take(book3) }
1.times { reader4.take(book4) }

puts book0.title

最佳答案

您可以动态定义实例变量:

5.times do |i|
instance_variable_set(:"@reader#{i}", "library_name#{i}")
instance_variable_set(:"@book#{i}", "book_title#{i}")
end

puts @reader1
puts @book1
puts @book4

# => library_name1
# book_title1
# book_title4

另一种可能性是使用 method_missing 伪造局部变量,同时使用实例变量作为缓存:

def create_variable_or_use_cache(name, &block)
name = "@#{name}"
instance_variable_get(name) || instance_variable_set(name, block.yield)
end

def method_missing(sym,*p)
if sym=~/^reader(\d+)$/ then
create_variable_or_use_cache(sym){ "Create reader#{$1} here" }
elsif sym=~/^book(\d+)$/ then
create_variable_or_use_cache(sym){ "Create book#{$1} here" }
else
super
end
end

puts reader1
puts reader1
puts book3
wrong_method

# =>
# Create reader1 here
# Create reader1 here
# Create book3 here
# binding.rb:13:in `method_missing': undefined local variable or method `wrong_method' for main:Object (NameError)

这是一个有趣的 Ruby 练习,但我不确定您是否应该使用它。

关于ruby - 如何在main中动态创建局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40556288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com