Skip to content

Instantly share code, notes, and snippets.

@pawurb
Last active December 24, 2015 09:19
Show Gist options
  • Save pawurb/6776558 to your computer and use it in GitHub Desktop.
Save pawurb/6776558 to your computer and use it in GitHub Desktop.
Ruby mixed ideas
#Metaprogramming
class Meta
def create_method(name, block)
self.class.send(:define_method, name, block)
end
end
m = Meta.new
method_body = -> { puts "hello no args" }
another_method_body = lambda { |text| puts "args are: #{text}" }
m.create_method(:a, method_body)
m.create_method(:b, another_method_body)
m.a
m.b "i arg!"
String.send(:define_method, :dupcase, -> { "DUPA " + self.to_s + " DUPA" })
# Example 8
class CarModel
# define a class macro for setting features
def self.features(*args)
args.each do |feature|
attr_accessor "#{feature}_price", "#{feature}_info"
end
end
# set _info and _price methods for each of these features
features :engine, :wheel, :airbag, :alarm, :stereo
end
#Procs
proc_one = ->(n) { n * 2 }
[1,2,3,4].map(&proc_one)
proc_two = Proc.new { |arg='default'| puts "Bloc called with: #{arg}" }
def caller(&block)
if block_given?
block.call
block.call(66)
end
end
caller(&proc_two)
class TexasHoldem::Game::Resolver
def initialize hands, board
@hands = hands
@board = board
end
def ranking
@hands.each(&assign_score)
@hands.group_by(&score_value).map(&by_hand)
end
private
def assign_score
lambda { |hand| hand.best_hand = TexasHoldem::Hand::Resolver.new(hand, @board).best_hand }
end
def score_value
->(hand) { hand.best_hand.score[0] }
end
def by_hand
->(key) { key[1] }
end
end
#hash possible keys
>> class Dupa
>> end
=> nil
>> d = Dupa.new
=> #<Dupa:0x007fddad10dbe0>
>> { d => 1 }
=> {#<Dupa:0x007fddad10dbe0>=>1}
>> { d => 1, Dupa => 2 }
=> {#<Dupa:0x007fddad10dbe0>=>1, Dupa=>2}
>> h = { d => 1, Dupa => 2 }
=> {#<Dupa:0x007fddad10dbe0>=>1, Dupa=>2}
h[dupa.class]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment