Tag Archives: ruby

Ruby: Executing code only if file was called directly

I wanted a way to treat a Ruby file as both an importable library or a script. The best solution I could find was as follows:

if __FILE__ == $0
   #script / run as self code goes here

If the file is called directly a la ruby ./library.rb, the code within that if block will be executed. If included, __FILE__, the file that this code exists in will not match $0, the file being executed and the code in that block will not be executed.


PHRASE = "Hello World"
def get_phrase
if __FILE__ == $0
 puts "Executing library.rb"
 puts get_phrase
require "library.rb"
puts "Executing script.rb"
puts get_phrase

Running ruby script.rb will produce:

Executing script.rb
Hello World

Running ruby library.rb will produce:

Executing library.rb
Hello World

It seems trivial but I’ve utilized this several times while creating large collections of scripts.

Ruby: Use .each on anything

While parsing several variables that could be strings or arrays of strings, I found myself doing too much type checking and my code was getting ugly. I wished there was a way to execute each on types that weren’t containers. For instance:

#define variables
$some_path = "/path1"
$some_path2 = ["/path2", "/path3"]
# ... some time later ...
$some_path.each {|path| puts path}
$some_path2.each {|path| puts path}

That should produce:


Turns out, this is easy to do. Simply add the each method to the Object class:

class Object
  def each(ary)
    yield self
    return ary

I’m not concerned with the index, so this works just fine for my needs