简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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