首页 > 解决方案 > Ruby 只执行第一行?

问题描述

我正在编写一个 ruby​​ 脚本并发现了这种奇怪的行为。

使用ruby 2.4.2 [x86_64-darwin16]

基本上我正在尝试回显两条单独的消息,并在我的index.rb文件中得到:

exec("echo 'teste'")
exec("echo 'teste2'")

但是当我跑步时ruby ./index.rb

输出是:

teste

为什么会这样?

这不应该是输出吗?

testeteste2

标签: rubyshellexec

解决方案


exec([env,] command... [,options])

通过运行给定的外部命令docs替换当前进程

这意味着第一次调用 用exec替换您的 ruby​​ 程序echo,因此不会执行 ruby​​ 程序的其余部分。

您可以使用反引号来运行您想要的命令:

`echo 'teste'`
`echo 'teste2'`

推荐阅读