当前位置:  开发笔记 > 后端 > 正文

是不是迭代一个恒定的最佳实践?

如何解决《是不是迭代一个恒定的最佳实践?》经验,为你挑选了1个好方法。

在我的Ruby脚本中,我在方法之外声明一个常量:

SYNDICATIONS = %w(Advanced Syndication, Boxee feed, Player MRSS, iPad MRSS, iPhone MRSS, YouTube)

并在以下方法中迭代它:

def some_method
   SYNDICATIONS.each do |syndication|
      puts syndication
   end
end

是不是一个好主意迭代?



1> Sergio Tulen..:

迭代没有错.但是,常量的定义存在错误.%w运算符不会像你想象的那样工作.它在空格上分割标记,而不是逗号.如果您希望空间不是分隔符,则将其转义.比较这三个例子,看看哪个最清楚.

a1 = %w(Advanced Syndication, Boxee feed, Player MRSS, iPad MRSS, iPhone MRSS, YouTube)
a1 # => ["Advanced", "Syndication,", "Boxee", "feed,", "Player", "MRSS,", "iPad", "MRSS,", "iPhone", "MRSS,", "YouTube"]

a2 = %w(Advanced\ Syndication Boxee\ feed Player\ MRSS iPad\ MRSS iPhone\ MRSS YouTube)
a2 # => ["Advanced Syndication", "Boxee feed", "Player MRSS", "iPad MRSS", "iPhone MRSS", "YouTube"]

a3 = ["Advanced Syndication", "Boxee feed", "Player MRSS", "iPad MRSS", "iPhone MRSS", "YouTube"]
a3 # => ["Advanced Syndication", "Boxee feed", "Player MRSS", "iPad MRSS", "iPhone MRSS", "YouTube"]

推荐阅读
手机用户2402852387
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有