gpt4 book ai didi

ruby-on-rails - 如何将方法属性存储在变量中

转载 作者:太空宇宙 更新时间:2023-11-03 17:23:31 25 4
gpt4 key购买 nike

class Dates
ATTRS = {date_from: '', date_to: ''}

def set_dates(ATTRS)
@date_from = date_from
@date_to = date_to
end

def show_dates(ATTRS)
p date_from
p date_to
end
end

Dates.new.set_dates(date_from: Time.current, date_to: Time.current)
#-:4: formal argument cannot be a constant
# def set_dates(ATTRS)
# ^
#-:9: formal argument cannot be a constant
# def show_dates(ATTRS)

SO 问题是:是否可以将方法属性存储在变量中?

最佳答案

您可以在 Ruby 2.0 中使用新的关键字参数语法:

class Dates
def set_dates(date_from: '', date_to: '')
@date_from = date_from
@date_to = date_to
end
def show_dates
p @date_from
p @date_to
end
end

或者Ruby 2.0之前的哈希参数:

class Dates
ATTRS = {date_from: '', date_to: ''}
def set_dates(attr)
attr = ATTRS.merge(attr)
@date_from = attr[:date_from]
@date_to = attr[:date_to]
end
def show_dates
p @date_from
p @date_to
end
end

对于 show_dates 方法,我猜你的意思是显示 Dates 实例的状态,所以我对它做了一些修改。

此外,在 Ruby 中,以大写字母开头的变量被视为常量,您不能将其用作方法的形式参数。

关于ruby-on-rails - 如何将方法属性存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22168263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com