Ruby 模仿 ES6 的简洁属性表示法

42thcoder · March 23, 2016 · Last by mizuhashi replied at March 24, 2016 · 2429 hits

es6 中有个很实用的语法糖:允许直接写入变量和函数,作为对象的属性和方法。

var foo = 'bar';
var baz = {foo};
baz // {foo: "bar"}

// 等同于
var baz = {foo: foo};

尝试用 Ruby 模拟了一下,语法不太漂亮,大家给点意见。

class TwinHash
  def self.call(&block)
    context, *array = yield

    Hash.new.tap do |hash|
      array.each do |ele|
        hash[ele] = context.local_variable_get(ele)
      end
    end
  end
end

class Array
  def to_hash(context)
    Hash.new.tap do |hash|
      each do |ele|
        hash[ele] = context.local_variable_get(ele)
      end
    end
  end
end



a_long_key_i_do_not_want_to_type_twice = 'test'
key = 'another one'


# 正常写法 
{ a_long_key_i_do_not_want_to_type_twice: a_long_key_i_do_not_want_to_type_twice, key: key }

# 模拟 es6
TwinHash.call{ [binding, :a_long_key_i_do_not_want_to_type_twice, :key] }

# 更少单词
%i(a_long_key_i_do_not_want_to_type_twice key).to_hash(binding)


# 输出结果
=> {:a_long_key_i_do_not_want_to_type_twice=>"test", :key=>"another one"}

有没有办法不传入 binding

太麻烦了,直接可以做成 t{a; b}这样

set_trace_func 拿 binding,eval 一下就可以了

You need to Sign in before reply, if you don't have an account, please Sign up first.