Skip to content

Instantly share code, notes, and snippets.

View hannestyden's full-sized avatar

Hannes Tydén hannestyden

  • Stockholm, Sweden
View GitHub Profile
class Hash
alias_method :[], :fetch # !> method redefined; discarding old []
end
h = {a: 1}
h[:a] # => 1
h[:b] rescue $! # => #<KeyError: key not found: :b>
h[:b, 2] # => 2
class E < StandardError; end
def m(raise_exception)
y do
r(raise_exception)
:nothing_raised
end
rescue E
:rescued
end
# # Adventures in `flat_map` land
#
# Investigating the conceptual difference between Ruby's `flat_map` and Scala's `flatMap`.
#
# Ruby's `flat_map`
a = [[1], [2], [[3]], [[4], 5], [[[6]]]]
a.flat_map { |e| e.first } # => [1, 2, 3, 4, [6]]
# ... which is the same as ...
a.map { |e| e.first }.flatten(1) # => [1, 2, 3, 4, [6]]
# Emulating `sed` with inplace editing **without** backups for OS X
# Tested with zsh.
sedi () {
local ext='.sedi-bak'
sed -i $ext $@
rm "${@: -1}$ext"
}
module DeepCompact
def self.blank?(o)
o.nil? || (o.respond_to?(:empty?) && o.empty?)
end
module Array
def deep_compact
map.with_object(self.class.new) { |e, o|
o << (e.respond_to?(:deep_compact) ? e.deep_compact : e)
}.select { |value| !DeepCompact.blank?(value) }
def scream(s)
s.upcase
end
array = %w[i scream u scream we all scream for icecream]
## "On" the object
array.map(&:upcase)
# => ["I", "SCREAM", "U", "SCREAM", "WE", "ALL", "SCREAM", "FOR", "ICECREAM"]
array.map { |c| c.method(:upcase).call }
class Fixnum
def +@
2
end
def -@ # !> method redefined; discarding old -@
-2
end
def +(o) # !> method redefined; discarding old +
# dog = cat || less
dog () {
a=$(</dev/stdin)
echo $a | $((($(echo $a | wc -l) < $LINES)) && echo cat || echo less)
}
@hannestyden
hannestyden / spake.sh
Last active August 29, 2015 14:01
Make with space
# Make with double space instead tabs.
spake () {
cat Makefile | sed 's/ /\t/g' > Spakefile
make -f Spakefile $@
rm Spakefile
}
tmush-first-window() {
session_name=$1
window_name=$2
cmd=$3
work_dir=$4
start_window=$window_name
if [[ "$work_dir" != "" ]]; then
cd "$work_dir"