来自外部 shell 命令的 Ruby 变量
我正在使用名为 artii 的 gem ( http://rubygems.org/gems/artii ) 来创建来自文本的 ascii 艺术图像。
我似乎只能使用 system() 来调用它,但是我想在网页中将结果显示为文本
的 .rb 文件:
def makeText
@word = system('artii Hello World')
puts @word
@word
end
puts
的结果:
=> _ _ _ _
=> | | | | | | |
=> | |__| | ___| | | ___
=> | __ |/ _ \ | |/ _ \
=> | | | | __/ | | (_) |
=> |_| |_|\___|_|_|\___/
然后,在我的 haml 文件中:
#{makeText}
=> true
我 有没有办法从命令行获取结果并将其转换为字符串、数组或散列以在网页中显示?
谢谢!
I’m using a gem called artii ( http://rubygems.org/gems/artii ) that creates ascii art images from text.
I can only seem to call it using system(), however I’d like to display the result as text in a webpage
My .rb file:
def makeText
@word = system('artii Hello World')
puts @word
@word
end
result of puts
:
=> _ _ _ _
=> | | | | | | |
=> | |__| | ___| | | ___
=> | __ |/ _ \ | |/ _ \
=> | | | | __/ | | (_) |
=> |_| |_|\___|_|_|\___/
Then, in my haml file:
#{makeText}
=> true
Is there a way to take the result from the command line and convert it to a string, array, or hash to display in a webpage?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想使用 反引号 而不是
系统
方法。只需将 shell 命令括在反引号中,返回值将是一个字符串,其中包含它输出到标准输出的任何内容。注意:请注意,不要在未先清理用户输入的情况下将用户输入传递到 shell,以防止恶意用户执行任意 shell 命令。只要您是提供反引号字符串的人,而不是用户,就可以了。
You want to use backticks rather than the
system
method. Just enclose your shell command in backticks, and the return value will be a string containing whatever it output to standard out.Note: Be careful not to pass user input to the shell without sanitizing it first, to prevent malicious users from executing arbitrary shell commands. As long as you're the one supplying the string in backticks, and not the user, you're fine.
对我来说,使用
system
或反引号将 gem 称为外部命令似乎很荒谬。您可以从 Ruby 将其用作 Ruby 库,无需任何系统交互。最简单的调用是:如果您想要更复杂的调用(即不同的字体、样式等),请查看 该 gem 的文档。
It seems ridiculous to me to call the gem as external command, either using
system
or backticks. You can use it from Ruby as a Ruby library, without any system interaction. The simplest invocation would be:If you want more complex invocation (i.e. different fonts, styles, etc), then check out that gem's documentation.