代码之家  ›  专栏  ›  技术社区  ›  Joe Morano

是否可以动态调用属性?

  •  1
  • Joe Morano  · 技术社区  · 7 年前

    假设我有一个模型 Person 具有任意数量的属性,包括 name . 是否可以通过使用变量指定属性来动态选择要调用的属性?像这样:

    person.name = "Jake"
    attr = "name"
    puts person.attr
    => "Jake"
    

    我可以用这样的条件语句来实现:

    if attr == "name"
      puts person.name
    elsif attr == "height"
      puts person.height
      ...
    

    但这似乎效率很低。

    2 回复  |  直到 7 年前
        1
  •  3
  •   Josh Brody    7 年前

    []

    person = Person.last
    attr = "height"
    puts person[attr]
    

    Person.columns_hash

    public_send

    person = Person.last
    attr = 'height'
    puts person.public_send(attr.to_sym)
    

    attr = params[:attribute] ?attribute=destroy

        2
  •  2
  •   Phlip    7 年前

    person.send(:height)