Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby Snippets
# Ruby classes
# Class inheritance
class Word < String
def palindrome?
self == self.reverse
end
end
s = Word.new("level")
puts s.length
puts s.palindrome?
puts s.class.superclass.superclass.superclass
# Modifying built-in classes
class String
def palindrome?
self == self.reverse
end
end
puts "deified".palindrome?
class String
def shuffle
self.split("").shuffle.join
end
end
puts "foobar".shuffle
# # Blocks
#
# (1..5).each { |i| puts i * 2 }
#
# (1..5).each do |num|
# puts num * 2
# end
#
# 3.times { puts "hello world" }
#
# (1..5).map { |i| puts i**2 }
#
# %w[a b c].map { |char| puts char.upcase }
#
# puts ("a".."z").to_a.shuffle[0..7].join
#
#
# # Hashes & Symbols
#
# puts user = { "first_name" => "foo", "last_name" => "bar" }
#
# user = { :name => "foobar", :email => "foobar@example.com" }
# puts user[:email]
#
# params = {}
# params[:user] = user
# puts params[:user][:email]
#
# flash = { :success => "it worked!", :error => "it failed." }
# flash.each do |key, value|
# puts "key #{key.inspect} has value #{value.inspect}"
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.