Skip to content

Instantly share code, notes, and snippets.

View hyfather's full-sized avatar

Nikhil Mungel hyfather

View GitHub Profile
@hyfather
hyfather / splat.rb
Created October 24, 2011 13:49
Demonstrates how the splat operator works in Ruby.
lambda{|*args| args}.call(1, 2)
#=> [1, 2]
# This is the splat operator used in the 'collecting mode'.
# The splat before the args ensured that all arguments were marshalled into an Array.
[1, 2, [3, 4]]
#=> [1, 2, [3, 4]]
[1, 2, *[3, 4]]
#=> [1, 2, 3, 4]
# This is the unmarshalling 'mode' of the splat operator.
@hyfather
hyfather / array_map.rb
Created October 24, 2011 13:06
Demonstrates how :map can be used on class:Array
[:a, :b, :c].map {|e| e.to_s }
#=> ['a', 'b', 'c'] # Invoke .to_s on each element and collect these in an array.
[:a, :b, :c].map(&:to_s)
#=> ['a', 'b', 'c'] # The same result obtained in a shorthand fashion.
@hyfather
hyfather / hashes_and_ararys.rb
Created October 24, 2011 12:41
Demonstrates how to form Hashes from Arrays in Ruby.
{:a => 'alpha'}.to_a
#=> [[:a, "alpha"]] # Notice the nested array
Hash[:a => 'alpha']
#=> {:a => 'alpha'}
Hash[[:a => 'alpha']]
#=> {} # Doesn't work with a nested array.
Hash[[[:a => 'alpha']]]
@hyfather
hyfather / flatten_hashes.rb
Created October 18, 2011 11:53
[Ruby] Merge all the hashes inside an Array into one big hash
class Array
def flatten_hashes
Hash[*self.map(&:to_a).flatten]
end
end
[{:a => 'alpha'}, {:b => 'beta'}, {:c => 'charlie'}].flatten_hashes
#=> {:a => 'alpha', :b => 'beta', :c => 'charlie'}
@hyfather
hyfather / minusminusversion.sh
Created September 12, 2011 16:22
I redirect this snippet's output into a version file that forms for good metadata about a deployable package which usually doesn't have the git repository along with it.
git log HEAD^..HEAD --format="%an pushed change %h on %aD.%n%nWhat's in this change?%n%s%n"
@hyfather
hyfather / ssh-copy-id
Created June 9, 2011 11:11 — forked from achamian/ssh-copy-id
Copy public key to authorized_keys
#!/usr/bin/env sh
# Copy public key to authorized_keys of a remote machine
if [ -z $1 ];then
echo "Usage"
echo "ssh-copy-id hostname /path/to/public/key"
exit
fi
if [ -z $2 ]; then
KEYCODE=`ssh-add -L`