gpt4 book ai didi

ruby - 使用注入(inject)方法查找最长的单词

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

找到最长的单词。

longest = %w{cat sheep bear}.inject do |memo, word|
memo.length > word.length ? memo : word
end

我猜测 memo 将以值 "cat" 开始,因为 inject 没有收到任何参数。我还猜测 word 的第一个值将是 sheep,然后是 wordbear

我没有关注 block 中发生的事情及其语法。如果有人可以详细说明,我将不胜感激。

最佳答案

<强>1。所以我猜 memo 将从值 cat 开始,因为 inject 没有传递给它的参数。

Documentation says:

If you do not explicitly specify an initial value for memo, then thefirst element of collection is used as the initial value of memo.

<强>2。我还猜测第一个词将是绵羊..然后是下一个词,熊。

您可以使用 puts 检查每个阶段禁止最终分配,但这只是 inject 方法的返回值:

longest = %w{ cat sheep bear }.inject do |memo, word|
puts "memo is currently #{memo}",
"word is currently #{word}",
"-----------------------"
memo.length > word.length ? memo : word
end

#memo is currently cat
#word is currently sheep
#-----------------------
#memo is currently sheep
#word is currently bear
#-----------------------

longest #=> "sheep"

另一种方式

最后是另一种更像 Rubyish 的方式来获取最长的单词:

%w{ cat sheep bear }.max_by(&:length) #=> "sheep"

关于ruby - 使用注入(inject)方法查找最长的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44618878/

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