首页 > 解决方案 > 测试 ruby​​ 的 Dome 管道

问题描述

我正在测试圆顶上练习并遇到这个问题我不知道如何使用 lambda 但我仍然尝试所以我不知道我是否正确。这是说明:

作为数据处理管道的一部分,完成管道方法的实现:

该方法应该接受可变数量的函数,并且它应该返回一个接受一个参数 arg 的新函数。

返回的函数应该使用参数 arg 调用管道中的第一个函数,并使用第一个函数的结果调用第二个函数。

返回的函数应该按照相同的模式继续按顺序调用管道中的每个函数,并从最后一个函数返回值。

例如,然后使用应该 returnpipeline(-> (x) { x * 3 }, -> (x) { x + 1 }, -> (x) { x / 2 })调用返回的函数。35

这是我的代码。

def pipeline(*funcs)
  -> (arg) {
    counter = 0
    temp = 0
    funcs.each do |func|
      if counter == 0
        temp += func.call(arg)
        counter += 1
      else
        temp = func.call(temp)
      end
    end
    return temp
  }
end

fun = pipeline(-> (x) { x * 3 }, -> (x) { x + 1 }, -> (x) { x / 2 })
puts (fun.call(3)) 
Output:

Run OK


5

但我得到了这个错误。

done Example case: Correct answer 
error  Various functions: TypeError: pipeline.rb:7:in `+' 
error  Various data types: TypeError: pipeline.rb:7:in `+' 

如果你很好奇,这里的问题是免费的。

https://www.testdome.com/d/ruby-interview-questions/6

这是起始代码:

def pipeline(*funcs)
  -> (arg) {
    # write your code here  
  }
end

fun = pipeline(-> (x) { x * 3 }, -> (x) { x + 1 }, -> (x) { x / 2 })
puts (fun.call(3)) # should print 5

标签: ruby

解决方案


您所需要的只是减少函数数组。

def pipeline(*args)
  ->(x) { args.reduce(x) { |acc, f| f.(acc) } }
end
fun = pipeline(-> (x) { x * 3 }, -> (x) { x + 1 }, -> (x) { x / 2 })
#⇒ #<Proc:0x0000561a73f48768@(pry):36 (lambda)>
fun.(3)
#⇒ 5

推荐阅读