我正在尝试缩短我的Ruby代码。
def count_palindromes_in_an(array)
palindromes = 0
array.each { |word| palindromes += 1 if word == word.reverse }
return palindromes
end
以便在每个方法执行的块内实例化回文。有些东西;
def count_palindromes_in_an(array)
array.each { |word| (palindromes != nil ? palindromes += 1 : palindromes = 1) if word == word.reverse }
return palindromes
end
然而,这会返回undefined method 'palindromes'
的错误。任何提示都感激不尽。
答案 0 :(得分:9)
这不会起作用,因为块会创建一个新范围。块内定义的变量与外部范围隔离。
[1].each do
palindromes = 1
local_variables #=> [:palindromes]
end
local_variables #=> []
要计算数组元素,请使用Array#count
:
array.count { |word| word == word.reverse }
您甚至可以向palindrome?
添加String
方法:
class String
def palindrome?
self == reverse
end
end
将您的代码缩短为:
array.count(&:palindrome?)