类似于 let in Ruby

2023-11-29

我曾经编写类似 let 的表达式——具有词法范围。

所以我自己写了(悲伤,但它会因多线程而失败):

# Useful thing for replacing a value of
# variable only for one block of code.
# Maybe such thing already exist, I just not found it.
def with(dict, &block)
  old_values = {}

  # replace by new
  dict.each_pair do |key, value|
    key = "@#{key}"
    old_values[key] = instance_variable_get key
    instance_variable_set key, value
  end

  block.call

  # replace by old
  old_values.each_pair do |key, value|
    instance_variable_set key, value
  end
end

我在谷歌中搜索 ruby​​ 的此类结构(可能是附加块定义),但找不到它。也许我失去了一些东西?在这种情况下,红宝石人使用什么?

PS:抱歉我的英语不好,你知道的。

UPD:我忘了提供用法示例:

@inst_var = 1
with :inst_var => 2 do
  puts @inst_var
end
puts @inst_var

output:

2
1

An idea:

class Object
  def let(namespace, &block)
    namespace_struct = Struct.new(*namespace.keys).new(*namespace.values)
    namespace_struct.instance_eval(&block)
  end
end

message = let(language: "Lisp", year: "1958", creator: "John McCarthy") do
  "#{language} was created by #{creator} in #{year}"
end

单值范围更明确,因为您在块参数中命名变量。这个抽象被称为as, pipe, into, scope, let, peg,...,凡是你能想到的,都是一样的:

class Object
  def as
    yield self
  end
end

sum = ["1", "2"].map(&:to_i).as { |x, y| x + y } #=> 3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类似于 let in Ruby 的相关文章

随机推荐