加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

DRY for Ruby变量循环

发布时间:2020-12-17 02:49:37 所属栏目:百科 来源:网络整理
导读:我有一个像下面的rubydef. 我可以做些什么让它变干吗?喜欢: [e,t,l,te,le,le].each |xxx| do if xxxend 这意味着为“变量”做循环,而不仅仅是“枚举器”. 码: def findLogs (obj) if e=obj['E'] e=obj['E']['pkg'] ? "@E = #{obj['E']['pkg']},":nil else
我有一个像下面的rubydef.
我可以做些什么让它变干吗?喜欢:

[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,le = %w|E T L Te Le|.map do |s|
  obj[s] &&?obj[s]['pkg'] ? "@#{s} = #{obj[s]['pkg']}," : nil
end

对于Sergio Tulentsev:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读