代码之家  ›  专栏  ›  技术社区  ›  Sergey

Ruby:使用Object.send指定变量

  •  16
  • Sergey  · 技术社区  · 15 年前

    有没有办法做这样的事?

    a = Struct.new(:c).new(1)
    b = Struct.new(:c).new(2)
    
    a.send(:c)
    => 1
    
    b.send(:c)
    => 2
    
    a.send(:c) = b.send(:c)
    

    最后一行导致错误:

    syntax error, unexpected '=', expecting $end
    a.send(:c) = b.send(:c)
                ^
    
    3 回复  |  直到 15 年前
        1
  •  28
  •   sepp2k    15 年前
    a.send(:c=, b.send(:c))
    

    foo.bar = baz 不是对方法的调用 bar 然后是赋值-这是对方法的调用 bar= . 所以你得告诉我 send 调用该方法。

        2
  •  5
  •   Weston Ganger    9 年前

    a.send(:c=, b.send(:c))
    

    如果 c 是一个动态变量,那么你可以这样做

    c = 'my_key'
    a.send("#{c}=", b.send(c))
    
        3
  •  4
  •   Adrian    15 年前

    a.send(:c=, b.send(:c))
    
    推荐文章