Skip to content

Instantly share code, notes, and snippets.

@fsword
fsword / reduce_sample.rb
Created August 27, 2013 13:30
reduce sample
class Order
attr_accessor :type, :sub_orders
def initialize type
self.type = type
self.sub_orders = []
end
# 统计订单及其包含子订单的数量,按照订单类型归类
def count_items
result = sub_orders.reduce({}) do |result, order|
@fsword
fsword / multi_try.erl
Last active December 10, 2015 02:28 — forked from anonymous/multi_try.erl
-module(multi_try).
-export([dothese/1]).
dothese(FuncArray) ->
Me = self(),
lists:foreach(fun(F) -> spawn(fun() -> F(Me) end) end, FuncArray),
spawn(fun() -> timer:sleep(200), Me ! timeout end),
Result = get_result("",length(FuncArray)),
io:format("result: ~p~n", [Result]).
@fsword
fsword / gist:4161295
Created November 28, 2012 13:29 — forked from acwright/gist:1944639
Sinatra / ActionMailer / Sendgrid / Heroku
require 'sinatra'
require 'action_mailer'
class Mailer < ActionMailer::Base
def contact
mail(
:to => "test@example.com",
:from => "test@example.com",
:subject => "Test") do |format|
format.text
@fsword
fsword / gist:3876987
Created October 12, 2012 02:25
ruby tailcall optimization
RubyVM::InstructionSequence.compile_option = {
tailcall_optimization: true,
trace_instruction: false
}
eval <<end
def fact(n, result = 1)
if n == 1
result
else
def foo
111
rescue
222
ensure
333
end
puts foo # got 111
module MyTool
module Tree
class << self
def loop root, &block
return false unless File.exist? root
block_given? ? exec(root, &block) : collect(root)
end
def exec root, &block
@fsword
fsword / prime_concurrent.rb
Created June 10, 2012 11:49
prime_concurrent.rb
require 'thread'
def prime n, concurrent_num=4
full_list = (2..n).to_a
prime_list = []
stop_index = (n ** 0.5).floor
last_prime = 2
while(last_prime < stop_index)
@fsword
fsword / prime_benchmark.rb
Created June 9, 2012 04:28
prime benchmark
require './prime.rb' # user defined function
require 'benchmark'
require 'digest/md5'
result = {
4 => 'ae5161e4645f5cd58897d32f529f3ad5',
5 => 'cf7b5007830f057a04d2b696527952e7',
6 => 'a43beaed59a26b8d85868eaa8fa2e972',
7 => 'c1aa9bda24aa8bc5473ca1f51c9fd106'
}
@fsword
fsword / prime.rb
Created June 8, 2012 16:51
求N以内的素数
def prime n
list = (2..n).to_a
(2...(n ** (0.5)).floor).each do |i|
list.delete_if{|e| e > i && e % i == 0}
end
list
end
@fsword
fsword / gist:2885903
Created June 7, 2012 01:16 — forked from feng92f/gist:2849163
google收录的敏感词