在我的 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
迭代一个常数是个好主意吗?
在我的 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"]
你不是在迭代常量——你是在一个数组上迭代,它恰好被一个常量引用。常量本身只是一种不打算重新分配的变量。但是你不处理常量本身——你处理它引用的对象。
所以问题变成了:遍历数组可以吗?
这个问题的明显答案是:是的。
除了%wSergio 指出的错误之外,该代码还可以工作,但是如果您拥有的特定代码是您要尝试使用的代码,那么这不是一个好方法。这会更好:
def some_method
puts SYNDICATIONS
end