DEV Community

loading...

Discussion on: Smooth Ruby One-Liners

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 Author

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!