gpt4 book ai didi

Ruby:方法帮助

转载 作者:太空宇宙 更新时间:2023-11-03 18:30:02 28 4
gpt4 key购买 nike

我是计算机科学专业的,我们刚开始学习 Ruby。我对我们应该解决的这个问题感到非常迷茫,主要是语法问题。这是我们要做的:

Write a method that takes an array of strings and a block and calls this block on each string. Recall that the keyword to call a block is yield. The syntax for the call is the following:

method(["blah", "Blah"]) {...}

Test the method by passing it a block that prints the result of applying reverse to each string. Print out the original array after the call. Test it again by passing a block that calls reverse!. Print out the original array. Observe the differences, explain them in comments.

我完全不知道如何解决这个问题。我对 block 和 yield 特别陌生。

最佳答案

def my_method(array, &block)
array.each{|a| yield a}
end

array = ["one", "two", "three"]
my_method(array) do |a|
puts a.reverse
end
#=> eno
#=> owt
#=> eerht
array
#=> ["one", "two", "three"]
my_method(array) do |a|
puts a.reverse!
end
#=> eno
#=> owt
#=> eerht
array
#=> ["eno", "owt", "eerht"]

关于Ruby:方法帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5629409/

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