Skip to content

Instantly share code, notes, and snippets.

@smsohan
Created November 12, 2010 05:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save smsohan/673781 to your computer and use it in GitHub Desktop.
Save smsohan/673781 to your computer and use it in GitHub Desktop.
Some advanced ruby features
#the new tap method of ruby will always return itself, but lets you play with!
data = (1..10).to_a
data.tap{|x| print x}.to_a.join(', ')
p
#alias will redirect method calls to method with a different name, useful for api changing
class SomeClass
def new_method(x)
p "The value is #{x}"
end
alias :old_method :new_method
end
SomeClass.new.old_method(20)
# Array.grep - the beauty of unix grep right into Ruby Array
puts((1..100).grep(38..44)) #=> [38, 39, 40, 41, 42, 43, 44]
c = IO.constants
puts c.grep(/SEEK/) #=> ["SEEK_END", "SEEK_SET", "SEEK_CUR"]
puts c.grep(/SEEK/) {|v| IO.const_get(v) } #=> [2, 0, 1]
#delegate - get rid of all the method declarations that just delegate others using Ruby's delegate support
require 'delegate'
class Actual
def a_method
puts "Method inside Actual"
end
end
class MyDelegator < DelegateClass(Actual)
def initialize
@actual = Actual.new
super(@actual)
end
end
MyDelegator.new.a_method
#freeze - make your variables pseudo readonly
my_hash = {:a => 1, :b =>2}.freeze
# my_hash[:a] = 20 #=> throws exception
#included vs. extended - included makes module methods your instance methods, extend will make the same methods as class methods
module AModuleToInclude
def self.included(mod)
puts "#{self} included in #{mod}"
end
def self.extended(mod)
puts "#{self} extended in #{mod}"
end
def a_method
puts "From a_method"
end
end
class AClass
include AModuleToInclude
extend AModuleToInclude
end
#this line makes use of the include
AClass.new.a_method
#this line makes use of the extend
AClass.a_method
#Use of * for argument list
def many_args(*args)
puts "Inside many_args = " ,*args
end
many_args( [1, 2, 3, 4])
#class_eval - write a code in string without making it look like a string using this
class ClassWithEval
class_eval <<-EVAL
def string_method(arg)
puts arg
end
EVAL
end
ClassWithEval.new.string_method('hi')
#instance_eval - write code as if your are right inside a class for your instance
class ClassWithInstanceEval
def initialize
@secret = 99
end
end
k = ClassWithInstanceEval.new
k.instance_eval { puts @secret } #=> 99
#inherited - fires this hook when a new subclassing takes place
class Foo
def self.inherited(subclass)
puts "New subclass: #{subclass}"
end
end
class Bar < Foo
end
class Baz < Bar
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment