ruby - 测试 ruby 的 Dome 管道
问题描述
我正在测试圆顶上练习并遇到这个问题我不知道如何使用 lambda 但我仍然尝试所以我不知道我是否正确。这是说明:
作为数据处理管道的一部分,完成管道方法的实现:
该方法应该接受可变数量的函数,并且它应该返回一个接受一个参数 arg 的新函数。
返回的函数应该使用参数 arg 调用管道中的第一个函数,并使用第一个函数的结果调用第二个函数。
返回的函数应该按照相同的模式继续按顺序调用管道中的每个函数,并从最后一个函数返回值。
例如,然后使用应该 return
pipeline(-> (x) { x * 3 }, -> (x) { x + 1 }, -> (x) { x / 2 })
调用返回的函数。3
5
这是我的代码。
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
解决方案
您所需要的只是减少函数数组。
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
推荐阅读
- docker - 如何使用fabric8 java客户端将docker镜像从私有注册表拉到镜像流下的open shift集群
- android - 我可以在 Android 移动应用程序中存储 mp3 文件吗
- azure - 无法运行 az container exec
- cen-xfs - cen/xfs 如何初始化 ptr_raw_data 以将代码页发送到打印机
- mysql - 组合没有公用表表达式的MYSQL查询
- javascript - Firestore 索引不起作用 - 使用索引已存在的相同索引链接响应
- c# - jtoken 字符串类型转换
- c - c - 设计线程安全库
- r - 将每个预测变量的 GLM 摘要制表,用于多个 GLM 拟合
- scala - Shapeless 的惰性和隐式参数