Here goes :-
files_with - Find files containing a string inside the current directory, recursively
files_with() { grep -H -n "$*" ./* -R | cut -d: -f1 -f2; }
$ files_with hello ./blah.txt:4 ./sub/blah.txt:6
files_with() { grep -H -n "$*" ./* -R | cut -d: -f1 -f2; }
$ files_with hello ./blah.txt:4 ./sub/blah.txt:6
=render "shared/cat_box", :locals => {:cat => @cat}
ActionView::Template::Error (undefined local variable or method `cat' for #<#<Class:0x1062afad8>:0x1062aa240>)
=render :partial => "shared/cat_box", :locals => {:cat => @cat}
class DynamicRow
def self.with_keys(keys)
result = Class.new
result.class_eval do
keys.each { |k| attr_accessor k }
def initialize(hash)
hash.each { |k, v| instance_variable_set :"@#{k}", v }
end
end
result
end
def self.benchmark
require 'benchmark'
sample_hash = {:a => "hello", :b => 3}
Benchmark.bm do|b|
b.report("OpenStruct ") do
50_000.times { OpenStruct.new(sample_hash) }
end
b.report("DynamicRow ") do
row_type = DynamicRow.with_keys(sample_hash.keys)
50_000.times { row_type.new(sample_hash) }
end
end
end
end
user system total real OpenStruct 13.400000 0.080000 13.480000 ( 13.572973) DynamicRow 0.570000 0.010000 0.580000 ( 0.584201)
user system total real OpenStruct 25.750000 0.160000 25.910000 ( 26.117587) DynamicRow 0.790000 0.010000 0.800000 ( 0.809647)
x = (do_something_that_might_raise rescue nil)
class Lexer
def initialize(str, matchers)
@str = str
@position = 0
@matchers = matchers
end
def consume
return Symbol.new(nil, 0, :end) if @position >= @str.length
part = @str[@position..-1]
@matchers.each do |m|
result = m.match(part)
if result
@position += result.length
return self.send :next if m.ignore?
return result
end
end
raise "Unable to lex: #{part}"
end
end
matchers = []
matchers << RegexMatcher.new(/(\s)+/, :whitespace, :ignore => true)
matchers << LiteralMatcher.new('+', :add)
matchers << LiteralMatcher.new('-', :subtract)
matchers << LiteralMatcher.new('*', :multiply)
matchers << LiteralMatcher.new('/', :divide)
matchers << LiteralMatcher.new('(', :left_paren)
matchers << LiteralMatcher.new(')', :right_paren)
matchers << RegexMatcher.new(/(\s)+/, :whitespace, :ignore => true, :)
lexer = Lexer.new("1 + 1 * 3.14159", matchers)
ExpressionLexer = Lexr.that {
ignores /\s+/ => :whitespace
matches /[-+]?[0-9]*\.?[0-9]+/ => :number, :convert_with => lambda { |v| Float(v) }
matches "+" => :addition
matches "-" => :subtraction
matches "*" => :multiplication
matches "/" => :division
matches "(" => :left_parenthesis
matches ")" => :right_parenthesis
}
lexer = ExpressionLexer.new("1 * 12.5 / (55 + 2 - 56)")
until lexer.end?
puts lexer.next
end
number(1.0) multiplication(*) number(12.5) division(/) left_parenthesis(() number(55.0) addition(+) number(2.0) subtraction(-) number(56.0) right_parenthesis()) end()