Skip to content

Commit b0a7854

Browse files
committed
added some more code, there are duplicates now that still need cleaned up
1 parent f9b128c commit b0a7854

File tree

1 file changed

+76
-1
lines changed

1 file changed

+76
-1
lines changed

snippets.rb

Lines changed: 76 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,79 @@ def reduce_by(percentage = 50.percent, &block)
7878
Integer(reduced_to)
7979
end
8080
alias_method :reduce, :reduce_by
81-
end
81+
end
82+
83+
# ---------
84+
85+
# @person ? @person.name : nil
86+
# vs
87+
# @person.try(:name)
88+
class Object
89+
def try(method)
90+
send method if respond_to? method
91+
end
92+
end
93+
94+
# ----------
95+
96+
class Percentage
97+
def chance
98+
Chance.new(self)
99+
end
100+
101+
class Chance
102+
attr_reader :odds, :happens
103+
alias :happens? :happens
104+
105+
def initialize(percent)
106+
@odds = percent.amount
107+
@happens = @odds > Kernel.rand(100)
108+
end
109+
110+
def of(&block)
111+
yield if happens?
112+
end
113+
end
114+
end
115+
116+
module Kernel
117+
def maybe(percent = 50.percent, &block)
118+
if block_given?
119+
percent.chance.of &block
120+
else
121+
percent.chance.happens?
122+
end
123+
end
124+
125+
def probably(&block)
126+
80.percent.chance.of &block
127+
end
128+
129+
def rarely(&block)
130+
20.percent.chance.of &block
131+
end
132+
end
133+
134+
# -----------
135+
136+
module Kernel
137+
def probably
138+
yield if (0...8).include? Kernel.rand(10)
139+
end
140+
141+
def rarely
142+
yield if (0...2).include? Kernel.rand(10)
143+
end
144+
end
145+
146+
1_000_000.times do
147+
probably do
148+
good
149+
end
150+
rarely do
151+
evil
152+
end
153+
end
154+
155+
# Good done 799,086 of 1,000,000
156+
# Evil done 199,662 of 1,000,000

0 commit comments

Comments
 (0)