我有方法header_components
,我想用这样的行为创建方法add_header_components
:
add_header_components << :buttons, after: :logo #=> [:logo, :buttons, :user_name]
header_components #=> [:logo, :user_name]
这是我尝试的:
# this method just return the array
def header_components
[:logo, :user]
end
def add_header_components(name, *args)
h = header_components
options = args.extract_options!
if options.keys.include?(:after)
index = header_components.index(options[:after])
h = header_components.insert(index+1, name.to_s)
elsif options.keys.include?(:before)
index = header_components.index(options[:before])
h = header_components.insert(index, name.to_s)
end
h
end
此方法有效,但我希望将多个name
参数传递给方法。
如果有任何方法可以使用此语法获取相同的数组:
header_components << :buttons, :search, after: :logo
答案 0 :(得分:0)
鉴于header_components
表现得像一个变量,为什么不把它变成一个呢?至于一次添加多个标头,您可以使用splat / double splat语法:
class Foo
attr_reader :header_components
def initialize
@header_components = ['logo', 'user']
end
def add_header_components(*headers, **options)
if options.keys.include?(:after)
index = @header_components.index(options[:after])
@header_components.insert(index+1, *headers)
elsif options.keys.include?(:before)
index = @header_components.index(options[:before])
@header_components.insert(index, *headers)
else
# I guess this should by default append all headers to the list?
@header_components.concat headers
end
end
end
f = Foo.new
f.header_components # => ['logo', 'user']
f.add_header_components('hello', 'world', after: 'logo')
f.header_components # => ['logo', 'hello', 'world', 'user']