reduce 与谓词
Coddy 面向 Go 开发者的 Ruby 课程的第 19 课,共 48 课。
Go 使用循环、显式单位元和提前退出来实现谓词和归约。Ruby 的 any? 和 all? 可以短路求值。对于空输入,all? 的结果为 true,因为没有元素不满足条件。归约的单位元也决定了空输入时的结果。选择单位元时,应根据运算的含义,而不是根据第一个方便的示例。
Go:完整程序
package main
import ("fmt";"strings")
func main(){
words:=[]string{"oak","elm"};any:=false;for _,word:=range words{if strings.HasPrefix(word,"e"){any=true;break}};fmt.Println(any)
all:=true;for _,value:=range []bool{}{if !value{all=false;break}};fmt.Println(all)
}
Ruby:完整程序
puts ["oak", "elm"].any? { |w| w.start_with?("e") }
puts [].all?挑战
简单输入是整数。只返回正整数的乘积。如果没有正整数,则返回 1。
从 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,同时独立检查必需的公共 API。
你的代码写在 exercise.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。
亲手试试
require_relative 'exercise'
def check(value)
raise 'Public API check failed' unless value
end
puts solve(STDIN.read)
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Go 开发者的 Ruby中的所有课
自己练习: Ruby 在线编译器