gpt4 book ai didi

ruby - Ruby 变量循环的 DRY

转载 作者:数据小太阳 更新时间:2023-10-29 07:26:39 24 4
gpt4 key购买 nike

我有一个像下面这样的 ruby​​ 定义。我可以做些什么让它变干吗?喜欢:

[e,t,l,te,le,le].each |xxx| do
if xxx
end

这意味着为“变量”做循环,而不仅仅是“枚举器”。

代码:

def findLogs (obj)
if e=obj['E']
e=obj['E']['pkg'] ? "@E = #{obj['E']['pkg']},":nil
else nil
end
if t=obj['T']
t=obj['T']['pkg'] ? "@T = #{obj['T']['pkg']},":nil
else nil
end
if l=obj['L']
l=obj['L']['pkg'] ? "@L = #{obj['L']['pkg']},":nil
else nil
end
if te=obj['Te']
te=obj['Te']['pkg'] ? "@Te = #{obj['Te']['pkg']},":nil
else nil
end
if le=obj['Le']
le=obj['Le']['pkg'] ? "@Le = #{obj['Le']['pkg']},":nil
else nil
end
end

最佳答案

e, t, l, te, le = %w|E T L Te Le|.map do |s|
obj[s] && obj[s]['pkg'] ? "@#{s} = #{obj[s]['pkg']}," : nil
end

对于塞尔吉奥·图伦采夫:

b = binding
%w|E T L Te Le|.each do |s|
b.local_variable_set(
s.downcase.to_sym,
obj[s] && obj[s]['pkg'] ? "@#{s} = #{obj[s]['pkg']}," : nil
)
end

关于ruby - Ruby 变量循环的 DRY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41160829/

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