Something like let in Ruby

后端 未结 2 1506
情书的邮戳
情书的邮戳 2021-01-21 14:18

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         


        
2条回答
  •  梦谈多话
    2021-01-21 14:45

    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
    

    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
    

提交回复
热议问题