在我的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
是不是一个好主意迭代?
迭代没有错.但是,常量的定义存在错误.%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"]