Created
August 23, 2010 23:07
-
-
Save darscan/546533 to your computer and use it in GitHub Desktop.
Some basic Ruby snacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Why Ruby is Fun | |
# Everything is an object | |
5.times {|x| puts x} | |
# Even nil is an object | |
puts nil.nil? | |
# Yes, nil is an object | |
nil.methods.each {|x| puts x} | |
# Convenient assignment | |
a, b, c = 1, 2, 3 | |
# Or even | |
array = ["apple", "banana", "carrot"] | |
a, b, c = array | |
puts a, b, c | |
# Swap 'em | |
a, b = b, a | |
# If statements can come last | |
puts "a is nil" if a.nil? | |
# Unless can be nice | |
puts "hello" unless a.nil? | |
# A Range is an object | |
puts (1..3) | |
# Range responds to each | |
("a".."z").each {|x| puts x} | |
# Each with index | |
"string".split("").each_with_index do |x, i| | |
puts "#{i}: #{x}" | |
end | |
# Arrays | |
array = [50, "foot", :dog, (1..4)] | |
array << "another element" | |
puts array | |
# Just add 'em | |
puts [1, 2, 3] + [4, 5, 6] | |
# Or multiply! | |
puts [1, 2, 3] * 3 | |
# Or flatten | |
puts [[1, 2, 3], ["a", "b", [:c, :d, [:e]]]].flatten | |
# The last element of an array | |
puts array[-1] | |
# A range of array elements | |
puts array[2..-1] | |
# You hiding something? | |
puts "found it!" if array.include? "foot" | |
# Anything at all? | |
puts "no elements" if array.empty? | |
# Flip it | |
puts array.reverse | |
puts "hello world!".reverse | |
# Capitalize | |
puts "hello world!".capitalize | |
# Radness | |
def func arg | |
p = Proc.new {return arg} | |
# the proc runs in this scope | |
# so return returns from this scope! | |
p.call | |
# won't get here! | |
puts "yo" | |
end | |
puts func "hi" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment