ruby-on-rails - Proc在不同范围内表现不同

标签 ruby-on-rails ruby

我是 ruby​​ 新手,开始学习 ruby​​,我来到了这个 proc 返回概念,我完全困惑了 proc 如何以不同的方式返回。

我在这里附上我的代码以供引用。 我也进行了谷歌搜索,但无法得到答案,如果有人可以帮忙的话。

def call_proc
    puts "Before proc"
    my_proc = Proc.new { return 2 }
    my_proc.call
    puts "After proc"
  end

  def proc_call
    def inside_call
        my_proc = Proc.new {return 4}
    end
    proc = inside_call
    proc.all
end

最佳答案

我看不出这两段代码有什么区别...但是,这一切似乎都按照预期的方式工作。无论您如何调用Proc,它们的工作方式都是相同的。

参见:https://www.codecademy.com/learn/learn-ruby/modules/learn-ruby-blocks-procs-and-lambdas-u/cheatsheethttps://www.rubyguides.com/2016/02/ruby-procs-and-lambdas/#Lambdas_vs_Procs

你的代码(和我的输出):

def call_proc
  my_proc = Proc.new { return 2 }

  puts "Before proc"
  my_proc.call
puts "After proc"
end

def proc_call
  def inside_call
    my_proc = Proc.new {return 4}
  end
  proc = Proc.new {return 4}

  puts "Before proc"
  proc.call
  puts "After proc"
end

输出:

2.7.2 :112 > call_proc
Before proc
 => 2
2.7.2 :113 > proc_call
Before proc
 => 4
2.7.2 :114 >

相比之下,如果您想在 Proc 之后继续操作,最好执行 Lambda:

def call_lambda
  my_lambda = -> { return 17 }

  puts "Before lambda"
  puts my_lambda.call
  puts "After lambda"
end

(注意调用之前的 puts,以及返回值 nil)

2.7.2 :122 > call_lambda
Before lambda
17
After lambda
 => nil

关于ruby-on-rails - Proc在不同范围内表现不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74421796/

相关文章:

ruby-on-rails - Postgres : prepared statement already exists

ruby-on-rails - Assets :precompile with uglify fails

ruby-on-rails - 自定义 RESTful 资源的 url_for(复合键;不仅仅是 id)

ruby-on-rails - 将时间戳添加到 db Rails 5+ 中的现有表

ruby - 如何在ruby代码中使用compass来编译项目? (不使用系统调用)

ruby-on-rails - 如何在 Rails 和 PostgreSQL 中有效地搜索匹配条件的最后一条记录?

ruby-on-rails - squeel 中的嵌套查询

ruby - 如何查看来自 HTTParty get 请求的响应 cookie?

ruby - 找到模块子项的更好方法?

ruby - Watir:查找包含特定子项的父 div