Some initial learnings from Ruby scripting
While scripting stuff, to load and use a module from the CLI:
irb -r <path to rb file>
Also, out of the box, irb
does not enable autocomplete and history. The fix is as easy as adding the following to .irbrc
:
require 'irb/completion' IRB.conf[:SAVE_HISTORY] = 10000
slop is a decent option parsing lib. General search online keeps leading one to OptionParser which is just way too much manual for a language as powerful as Ruby. This lib is a fine example of how a language should serve you.
To run some operation on an array concurrently, this simple formulation serves instead of reaching out specific external gems:
def Concurrently(src, &block) tids = src.map do |s| Thread.new do yield s end end tids.each do |tid| tid.join end end
Reopening standard classes is now one of my favorite move while scripting.
To make it easier to deal with folders and files:
class String def /(other) File.join(self, other.to_s) end end
This allows one to now refer to nested folders as easily as "toplevel"/dir/"output"
. Notice how we have mixed strings and vars easily.
Consider the following:
class Integer def seconds return self end def minutes return self * 60 end end
We can now use constructs like sleep 2.minutes
and sleep 15.seconds
.
When using rescue
, apparently you can retry
:
begin retries ||= 0 # main logic here rescue => e retry if (retries += 1) < 10 raise e end
This can easily be wrapped into a function with yield.
I use select
quite frequently and have founded the related (lesser known?) function detect
quite handy too. The latter is equivalent to finding a single element instead of filtering out an array.
Feeling the lack of tuples, but able to get away with just using arrays for now. This thankfully works with destructuring, so you can do things like a, b, c = [1, 1.04, "haha"]
.
Been using Faraday as a http client. Irrespective of what the comments say, its Connection
object does not seem to be thread safe, but otherwise no other complaints.