Skip to content

Instantly share code, notes, and snippets.

View mlomnicki's full-sized avatar

Michał Łomnicki mlomnicki

View GitHub Profile
@mlomnicki
mlomnicki / dont_forget_comma.rb
Created January 20, 2011 19:54
Comma vs implicit string concat
def foo(a = "hello", b = "stranger")
puts "#{a} #{b}"
end
foo("go" "away")
# << operator
original = "foo"
copy = original
copy << "bar"
copy # => "foobar"
original # => "foobar"
# += operator
original = "foo"
@mlomnicki
mlomnicki / arguments_count.rb
Created September 7, 2010 22:35
How to check how many arguments the method accepts
# How to check how many arguments the method accepts?
class Foo
def initialize
end
def bar(a,b)
@mlomnicki
mlomnicki / check)if_inherits.rb
Created August 6, 2010 08:42
check if class inherits
# Check if class inherits from antoher class
if Fixnum < Numeric
puts "Fixnum is a numeric"
else
puts "Fixnum is not a numeric"
end
@mlomnicki
mlomnicki / data_and_end.rb
Created April 20, 2010 00:24
inline data
require 'yaml'
puts "Want some magic?"
y = YAML::load(DATA)
puts y.inspect
__END__
---
@mlomnicki
mlomnicki / rest_of_array.rb
Created April 20, 2010 00:16
Rest of array
a, *b = [1,2,3,4]
# a = 1
# b = [2,3,4]
@mlomnicki
mlomnicki / string_to_proc.rb
Created April 20, 2010 00:11
String to proc
class String
def to_proc
eval "Proc.new { |*args| args.first#{self} }"
end
end
[1,2,3].collect(&'+5')
@mlomnicki
mlomnicki / block_comments.rb
Created April 19, 2010 23:48
Block comments
puts "Before block comment"
=begin
The method above prints a string to stdout
Pretty awesome!
And the method below does the same!
=end
puts "After block comment"
@mlomnicki
mlomnicki / string_regex.rb
Created April 19, 2010 23:41
regex as string index
s = 'michal@example.com'
s[/^([^@]+)@(.*)/, 1] # => michal
s[/^([^@]+)@(.*)/, 2] # => example.com
s.match(/^([^@]+)@(.*)/)[1] # => michal
s.match(/^([^@]+)@(.*)/)[2] # => example.com
@mlomnicki
mlomnicki / self_extend.rb
Created April 19, 2010 23:30
Self extending module
module Utils
def foo
puts "bar"
end
def bar
puts "foo"
end