像让Ruby一样 [英] Something like let in Ruby

查看:110
本文介绍了像让Ruby一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经写过类似let的表达式-具有词法作用域.

I used to write let-like expressions -- with lexical scope.

所以我写了我自己的(悲伤,但是它将在多个线程中失败):

So I write my own (sad, but it will fail with multiple threads):

# 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

我在google中搜索了ruby的此类构造(可能是其他块定义),但找不到.也许我松了点什么?在这种情况下,红宝石人们会使用什么?

I search in google for such constructions (maybe additional block definitions) for ruby, but can't found it. Maybe I loose something? What ruby-people use in such cases?

PS:对不起,我的英语不好,你知道.

PS: Sorry for my bad English, you know.

UPD:我想提供使用示例:

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

输出:

2
1

推荐答案

一个想法:

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

单值作用域更加明确,因为您在块参数中命名了变量.将该抽象称为aspipeintoscopeletpeg,...,命名相同,都是相同的:

Single-value scopping is more explicit because you name the variable(s) in the block arguments. This abstraction has been called as, pipe, into, scope, let, peg, ..., you name it, it's all the same:

class Object
  def as
    yield self
  end
end

sum = ["1", "2"].map(&:to_i).as { |x, y| x + y } #=> 3

这篇关于像让Ruby一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆