DEV Community

Cover image for Smooth Ruby One-Liners

Smooth Ruby One-Liners

Ryan Palo on October 09, 2017

When I first started learning Ruby, the first book I read had a chapter at the front about all of the command line options and flags for the ruby c...
Collapse
 
dmerand profile image
Donald Merand

This is great! So many helpful tips. I didn't know about the auto-split functions, for example, and will definitely use that one!

This article makes me think of Ryan Tomayko's awk-ward Ruby, which is worth a read if you haven't checked it out.

Collapse
 
rpalo profile image
Ryan Palo

That article is super interesting and really well written! Thanks for sharing. 😬 glad you liked my post

Collapse
 
learnbyexample profile image
Sundeep • Edited

Good one, liked the way concepts are introduced :)

Some note points:

1) $_ is default for regex match (also note the missing dot)

$ ruby -pe '$_strip! if $_ =~ /soup/' /home/rpalo/recipes
$ ruby -pe '$_.strip! if /soup/' /home/rpalo/recipes

2) Don't redirect output to same file as input, you'll be left with empty file

$ ruby -pe '$_.gsub!(/#.*$/, "")' .myconfig > .myconfig

See bash pit fall , stackoverflow, unix.stackexchange etc

3) As shown in last but one example, $_.gsub! can be shortened to gsub

4) Can also use indexing to get first/last element of array, i.e $F[0] and $F[-1] respectively

Collapse
 
rpalo profile image
Ryan Palo

Thanks! I think I've got most everything updated. That input-output redirect is especially good to know.

I left the F.first and F.last because I think they're a bit easier to read, and it's possibly a bit more idiomatic Ruby to use methods when they're available (like using item.zero? instead of item == 0). If you wanted the second item, $F[1] would be fair though.

Anyways, thanks for helping me make my post better, I really appreciate it!

Collapse
 
ariera profile image
Alejandro Riera

very cool!

Collapse
 
rpalo profile image
Ryan Palo

Thanks! Glad you liked it!