gpt4 book ai didi

ruby-on-rails - 什么时候 block 比函数更有用(ruby)?

转载 作者:数据小太阳 更新时间:2023-10-29 07:05:49 26 4
gpt4 key购买 nike

我有两个给出相同结果的例子。

带 block :

def self.do_something(object_id)
self.with_params(object_id) do |params|
some_stuff(params)
end
end

def self.with_params(object_id, &block)
find_object_by_id
calculate_params_hash
block.call(params_hash)
end

和方法:

def self.do_something(object_id)
some_stuff(self.get_params(object_id))
end

def self.get_params(object_id)
find_object_by_id
calculate_params_hash
params_hash
end

第二个解决方案似乎更直接,但我在我们的应用程序代码中发现了第一个的一些用法。我的问题是:在什么情况下推荐第一种?各有什么优缺点?

最佳答案

通常,当人们想要在另一段代码中运行一段代码时,他们会使用 block 。示例:

DB.with_shard_for_user(user_id) do |db|
# perform operations on a user's shard

end # shard is reverted back to original value

File.new(filename) do |file|
# work with file
end # file is closed automatically

User.transaction do
# run some operations as a single transaction
end

这些 block 在它们的词法上下文中是封闭的(它们从声明 block 的地方捕获变量,并将它们带到 block 被调用的地方)。

接受 block 的方法的示意结构。

def transaction
open_transaction # pre- part

yield if block_given? # run provided code

commit_transaction # post- part
rescue
rollback_transaction # handle problems
end

在您的第一个示例中, block 的使用可能是不合理的(恕我直言)。没有明显原因太复杂。

关于ruby-on-rails - 什么时候 block 比函数更有用(ruby)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9718350/

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