简体   繁体   English

Ruby命令行使用“ -e”开关,将问题打印到标准输出

[英]Ruby command line using “-e” switch, problem printing to stdout

I want to take a string of characters, parse out only the numbers, and then print that string of numbers to stdout. 我想要一个字符串,仅解析数字,然后将该数字字符串打印到stdout。 It has to be done with one line using the ruby -e switch on the command line. 必须使用命令行上的ruby -e开关用一行完成。 It must be one line because I'm using this as part of a applescript with the do shell script command. 它必须是一行,因为我将它用作do shell script命令的applescript的一部分。

Here's the code I came up with: 这是我想出的代码:

ruby -e '%{303-123-4567}.to_s.chars.to_a {|char| print char if char =~ /\\d/}'

I realize print is being called for each digit. 我意识到每个数字都需要打印。 It's Friday and my brain is fried. 今天是星期五,我的大脑炸了。 :-) Does anyone have any suggestions? :-) 有没有人有什么建议?

Thank you! 谢谢!

You could just use gsub : 您可以只使用gsub

$ ruby -e 'print %{303-123-4567}.gsub(/[^\d]/, "")'
3031234567

You are sending the block to the to_a method, that don't do any thing with a block. 您正在将块发送到to_a方法,该方法对块没有任何作用。 You can easly do: 您可以轻松做到:

%{303-123-4567}.each_char {|ch| print ch if ch =~ /\d/}

You can use scan too: 您也可以使用scan

%{303-123-4567}.scan(/\d/) {|num| print num}

Do you just need a .map in there? 您是否只需要一个.map?

ruby -e '%{303-123-4567}.to_s.chars.to_a.map {|char| print char if char =~ /\d/}'

Seems to do what you want. 似乎可以做您想要的。

(Disclaimer: I'm not a Ruby programmer so may have missed the point here!) (免责声明:我不是Ruby程序员,所以这里可能遗漏了重点!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM