Tag: proc

在Ruby中,你可以使用lambda或proc调用方法来调用迭代器吗?

我想创建一个迭代器,我可以传递给方法来调用。 #!/usr/bin/env ruby puts “————————————” puts “1 This works.” puts “————————————” 1.times {|who| puts “Position #{who} works!”} puts “————————————” puts “2 This works.” puts “————————————” aBlock = Proc.new { |who| puts “Position #{who} also works!” } 2.times &aBlock puts “————————————” puts “3 This works.” puts “————————————” def eachIndex 3.times { |i| yield i } end […]

在Ruby中传递的块中引用调用对象

有没有办法在被调用的块中获取被调用的对象。 例如,是否有任何方法可以让块访问方法batman或类SuperHeros class SuperHeros attr_accessor :news def initialize @news = [] end def batman task puts “Batman: #{task} – done” yield “feed cat” @news << task end end cat_woman = lambda do |task| puts "Cat Woman: #{task} – done" # invoker.news << task end robin = lambda do |task| puts "Robin: #{task} – done" # […]

我可以评估Proc中的块吗?

我可以在Proc中产生一个块吗? 考虑这个例子: a = Proc.new do yield end a.call do puts “x” end 我想要实现的是打印x ,但是用ruby 2.0解释这会引发LocalJumpError: no block given (yield) 。

当内省模块类时,“#map(&proc)”成语如何工作?

提出成语 我发现了一个有趣但无法解释的替代方案 。 代码显然适用于REPL。 例如: module Foo class Bar def baz end end end Foo.constants.map(&Foo.method(:const_get)).grep(Class) => [Foo::Bar] 但是,我并不完全理解这里使用的习语。 特别是,我不理解使用&Foo ,它似乎是某种闭包,或者#grep的这种特定调用如何对结果进行操作。 解析成语 到目前为止,我已经能够解析其中的一些部分,但我并没有真正看到它们如何组合在一起。 以下是我认为我对示例代码的理解。 Foo.constants返回模块常量数组作为符号。 method(:const_get)使用Object#方法执行方法查找并返回闭包。 Foo.method(:const_get).call :Bar是一个闭包,它返回类中常量的限定路径。 &Foo似乎是某种特殊的lambda 。 文档说: 如果proc对象由&参数给出,&参数将保留技巧。 我不确定我是否完全明白在这个特定背景下这意味着什么。 为什么选择Proc? 什么“诡计”,为什么这里有必要? grep(Class)正在对#map方法的值进行操作,但其function并不明显。 为什么这个#map构造返回一个greppable Array而不是Enumerator? Foo.constants.map(&Foo.method(:const_get)).class => Array 如何为名为Class的类的grepping实际工作,为什么这里需要特定的构造? [Foo::Bar].grep Class => [Foo::Bar] 问题,重申 我真的很想完全理解这个成语。 任何人都可以在这里填补空白,并解释这些碎片是如何组合在一起的吗?

将方法传递给迭代器方法时发生了什么

我们知道,wo可以通过&:前缀将方法传递给迭代器方法。 例如: [“a”, “b”].map(&:upcase) #=> [“A”, “B”] def rettwo 2 end [“a”, “b”].map(&:rettwo) #=> [2, 2] 这是问题所在,当我编写一个方法时,将一个带有&:前缀的方法传递给它,我收到一条错误消息:“ArgumentError:no receiver given”。 让我展示代码: def a_simple_method &proc puts proc.class # it shows `Proc` proc.call end def a_iterator_method puts yield end a_simple_method &:rettwo #=> ArgumentError: no receiver given a_iterator_method &:rettwo #=> ArgumentError: no receiver given 我缺少什么,像Array的方法这样的map如何处理它

在Ruby中,可以显式创建局部变量

例如 x = 123 p = Proc.new { x = ‘I do not want change the value of the outer x, I want to create a local x’ } 在Ruby中是否有与Perl中的“my”关键字相同的东西?

有没有更简洁的方法在Ruby中调用外部方法?

这样做有更简洁的方法吗? # Given a directory containing subdirectories: foo, bar targets = [‘./foo’, ‘./bar’, ‘./free’] targets.map{ |d| Dir.exists? d } # => [ true, true, false ] 我希望能够做类似于proc的事情…它感觉更干净: # targets.map( Dir.exists? )