gpt4 book ai didi

Ruby:在 block 中实例化一个新变量

转载 作者:太空宇宙 更新时间:2023-11-03 17:07:12 24 4
gpt4 key购买 nike

我正在尝试缩短我的 Ruby 代码。

def count_palindromes_in_an(array)
palindromes = 0
array.each { |word| palindromes += 1 if word == word.reverse }
return palindromes
end

这样回文在每个方法执行的 block 中被实例化。类似的东西;

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'。感谢收到任何提示。

最佳答案

这是行不通的,因为一个 block 创建了一个新的范围。 block 内定义的变量与外部范围隔离。

[1].each do
palindromes = 1
local_variables #=> [:palindromes]
end

local_variables #=> []

要对数组元素进行计数,请使用 Array#count :

array.count { |word| word == word.reverse }

您甚至可以向 String 添加 palindrome? 方法:

class String
def palindrome?
self == reverse
end
end

并将您的代码缩短为:

array.count(&:palindrome?)

关于Ruby:在 block 中实例化一个新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28405799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com