开发者

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. It has to be done with one line using the ruby -e switch on the command line. It must be one line because I'm using this as part of a applescript with the do shell script command.

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 开发者_如何学JAVAanyone have any suggestions?

Thank you!


You could just use 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. You can easly do:

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

You can use scan too:

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


Do you just need a .map in there?

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!)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜