6 ms·
Ruby One-Liners
- par 7y agoWhat about getting some Obfuscated Ruby one-liners, like the well known Perl Obfuscation Contests? https://www.foo.be/docs/tpj/issues/vol4_3/tpj0403-0017.html https://www.foo.be/docs/tpj/issues/vol4_3/tpj0403-0017.html :)
- creatonez 7y agoI think the natural successor to IOCCC and the Obfuscated Perl Contest is the Code Golf^1 community on stack exchange ^1: https://codegolf.stackexchange.com/questions?tab=Votes https://codegolf.stackexchange.com/questions?tab=Votes
- eyegor 7y agoMaybe I'm being pedantic, but half of these use ";" to separate statements so I wouldn't really call them one liners.
- tyingq 7y agoGuess you could replace ; with && for many of them. More typing though.
- kbenson 7y agoA one liner does not mean "one line of source code in a file", it means "a single shell statement". That's why the Ruby command is prefixing them all. I routinely write 10-20 statement Perl one-liners at work for one off things. For example, just yesterday it was to parse a log, grep for specific lines, pull out a time and a number per line, display name, number, and some number of characters afterwards as a quick abnd dirty graph of the magnitude to make it obvious if there were major outliers and to try to see trends over time. Still a one-liner.
- bdcravens 7y agoIn theory, couldn’t you then compile a Rails app into a one-liner? (Seems the max line length varies, but is at least hundreds of thousands of characters in most OSes)
- kbenson 7y agoYou could, but it would be stupid to do so if it wasn't a trivial app, since nobody wants to support something like that, even if it's lifetime is measured in minutes or hours. It's a one-liner, just a pointless one. That said, if rails has a super simple default startup that could serve a file, then it might be useful to start that as a one liner in select circumstances.
- vinceguidry 7y agoRails has generators for that. Invaluable for greenfielding projects in an iterative manner. Blow everything away and recreate with a single command. https://guides.rubyonrails.org/generators.html https://guides.rubyonrails.org/generators.html
- vcavallo 7y agonobody wants to support weird looking one-liners either
- eyegor 7y agoSure, but then you could refactor most programs into "one line" (similar to what another commenter pointed out). I was expecting more of a functional piping or chaining style as opposed to distinct statements and defining local variables.
- anonytrary 7y agoYou're not being pedantic. The term "one-liner" is a misnomer. In many languages, whether or not a program can fit on a single line is a pointless metric, since a program can be rewritten into a single line (e.g. with semicolons or commas). People use the term "one-liner" as if it meant "concise code" which isn't necessarily true. It would be more accurate to just say "concise code".
- Zhyl 7y agoI would expand on that and say 'concise code executed by directly invoking the parser in a shell-like environment using special flags such as a,n,p and e.'
- cgranier 7y agoI always liked this one I wrote ages ago, to generate strong (at the time) passwords: [code lang=“ruby”] ((33..126).map { |i| i.chr }).to_a.shuffle[0..14].join [/code]
- Axsuul 7y agoA bit more efficient: 14.times.map { rand(33..126).chr }.shuffle.join
- oh_sigh 7y agoAnd 3x more possibilities because it allows the same character more than once. But I think the last shuffle is not necessary
- cgranier 7y agoThanks! Learned something new today (even though I’m mostly on Python now)
- e12e 7y agoWhy shuffle? Does it do something rand doesn't already do? At any rate, would probably want to use https://ruby-doc.org/stdlib-2.5.1/libdoc/securerandom/rdoc/Securerandom.html https://ruby-doc.org/stdlib-2.5.1/libdoc/securerandom/rdoc/S... for password generation. Also, I think you might just want an alphabet and use sample: https://ruby-doc.org/core-2.5.1/Array.html#method-i-sample https://ruby-doc.org/core-2.5.1/Array.html#method-i-sample # unsure if you need a: require 'securerandom' (33..126).sample(14, random: SecureRandom).map(&:chr).join
- Axsuul 7y agoYou're right, probably doesn't need shuffle :)
- petepete 7y agoOr for readable/memorable ones File.readlines('/usr/share/dict/words').map(&:strip).shuffle.first(5).map(&:capitalize).join => "PanChloroformateParoticTillotBrushoff"
- draw_down 7y agoI would never be able keep straight the escaping for these incantations. Writing code at the shell is not fun.
- tyingq 7y agoNot really an issue unless the one liner itself has single quotes in it, or perhaps you're using Windows?
- j88439h84 7y agoI like to build lots of cool command-line one-liners in Python with the Mario tool. https://github.com/python-mario/mario https://github.com/python-mario/mario
- stevebmark 7y agoIf you're going to write unreadable code why not use Perl? It's much faster than Ruby. Or Awk, even though it's one of the worst programming languages ever created?
- aexl 7y agoWhy is awk one of the "worst programming languages ever created"?
- aledalgrande 7y agoThat's what I was thinking. Free to use Ruby any way you want, but this is not code I would be happy to see in my codebase.
- emmelaich 7y ago.. because you know Ruby and not Perl of course. Ruby (and Perl) can and probably should be used for many tasks where you might use awk and sed and don't particularly care about performance.
- pizza234 7y agoOne liners are not necessarily part of a codebase; one might use them for text processing on the fly. An argument "against readability" is culture. For sysadmins, Perl is a well-known language; it's not unreadable¹. Note that the same applies to Bash, and Bash scripts are still popular. This doesn't imply that Perl/Bash scripts should be universally used, but that within a certain culture, they make perfect sense. ¹=when talking about oneliners
- kbenson 7y agoI knew Ruby copied a lot from Perl, but I wasn't prepared for just how much these are exactly how you would do the same thing in perl, just with the the order of passing lists reversed. The command line switches are the same, the BEGIN/END block stuff is the same, the $F auto-splitting is the same. Good on Ruby, that's the stuff that makes Perl one-liners actually worth coming back to again and again.
- faitswulff 7y agoWhat is that BEGIN{...} and END{...} syntax? I've seen a good amount of Ruby, but haven't encountered that yet.
- jhbadger 7y agoIt's basically there to make Ruby an equivalent to AWK. It only makes sense if you are looping over the lines with -n. The BEGIN block runs at the start of the run, and the END block at the end. They are useful for things like initializing a sum variable to zero at the start and printing it out at the end.
- emmelaich 7y agoWhat really baked my noodle is that there is another "end" called __END__ used like this $ cat data.rb DATA.each_line { |ln|puts ln } __END__ fish cat dog $ ruby data.rb fish cat dog
- masklinn 7y agoIt's from awk: the BEGIN and END patterns match the start and end of a file/stream being processed, while normal patterns are checked on each line (and no pattern matches every line). This is very useful to script a setup -> for reach line -> summary of a file e.g. initialise a map in BEGIN, fill the map for each line, and print the map in END.
- pmontra 7y agoThat kind of Ruby is pretty different from the Ruby one use to write applications like Rails. For example, after 14 years of Ruby I have no idea of what $F is. I have to google it, and I did at least 10 years of Perl before that. I use Ruby for text processing now, because it's easier to read than Perl, but I loop on stdin with IO.readlines, each and split. It could be less efficient but I'm not parsing billions of records. I value readability more than one liners.
- bdcravens 7y agoOT: on mobile the authors bio fills up the entire screen. The headline is beneath the fold.
- asicsp 7y agoI made a compilation of Ruby one-liners [1] as well last year. There's plenty of stuff that is similar to Perl, which in turn had borrowed from awk, sed and other tools. The biggest difference I'd pick is Perl's context based operation. # Ruby requires explicit conversion with to_i ruby -ane 'print if $F[1].to_i > 35' perl -ane 'print if $F[1] > 35' Performance is slower compared to Perl, but to those who already know Ruby, this would suit better than learning the nuances of another language. [1] https://github.com/learnbyexample/Command-line-text-processing/blob/master/ruby_one_liners.md https://github.com/learnbyexample/Command-line-text-processi...
- Maledictus 7y agoI can't stand weak types, so I prefer Ruby even if it is a little longer. Thanks for pointing this out.
- pizza234 7y agoThere are other significant other functionalities that I find very handy in oneliners, notably: - automatic associative array instantiation - the return value of regular expressions with a capture group is the value matched by it (in Ruby, the closest to this is `[/regex/, <group_i>]`)
- empath75 7y ago1.upto(100){|n|puts'FizzBuzz'[i=n**4%-15,i+13]||n}
- edmoffo 7y agoThis is what I love Ruby for: one-liners! :) Thanks for the summary, truly helpful.