Skip to content

Instantly share code, notes, and snippets.

@rubydubee
rubydubee / working_inject_conditional.rb
Created June 27, 2013 15:29
always add else if you are writing conditional statement inside inject.
[35] pry(main)> total = words.inject(0){ |result, word| word.size > 3 ? word.size + result : result}
=> 14
[36] pry(main)>
@rubydubee
rubydubee / not_so_working_inject.rb
Last active December 19, 2015 01:39
Conditional code inside inject could be fatal!
[32] pry(main)> words = %w{mary had a little lamb}
=> ["mary", "had", "a", "little", "lamb"]
[33] pry(main)> total = words.inject(0){ |result, word| word.size + result}
=> 18
[34] pry(main)> total = words.inject(0){ |result, word| word.size + result if word.size > 3}
TypeError: nil can't be coerced into Fixnum
from (pry):52:in `+'
[35] pry(main)>
k = [1,2,3,4]
k.each do |c|
puts c
end
@rubydubee
rubydubee / AccountAction.java
Created April 19, 2012 23:00
Tiny MVC for J2EE
public class AccountAction implements Action
{
@Override
public void process(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//do your processing here, take values from DB, may be!
SomeBean user = new SomeBean("Paddy")
@rubydubee
rubydubee / Tree.rb
Created February 17, 2012 18:02
Tree with compare function, the insertion is quite complex but i just wanted it to work.
module Tree
class Node
attr_reader :word, :left, :right
include Enumerable
def initialize(value)
@word = value
@left = @right = nil
end
def insert(node, dir)
@rubydubee
rubydubee / Observable.rb
Created December 3, 2011 07:44
Observer and Duck type
class Observable
def initialize
@observers = []
end
def observe(o)
@observers << o
end
def called
@rubydubee
rubydubee / game_of_life.rb
Created September 6, 2011 20:52
Game of life in Ruby
=begin
Whenever we visit the cell in the pattern, we call this method
to get the next state of the cell when the Tick happens.
Here, we add the values of all the eight cells around the visited cell
and apply the game_of_life rules as specified in the comments below.
=end
def next_gen(seed, row, col)
next_state = 0
(-1..1).each do |xdir|
(-1..1).each do |ydir|
@rubydubee
rubydubee / rubyish_bc.rb
Created June 30, 2011 22:37
Rubyish BaseConverter
#To find the equivalent of 582 in base-14 NS do this :
582.to_s(14) #will return "2d8"
#and vice versa
"2d8".to_i(14) #will return 582
@rubydubee
rubydubee / baseconverter_example.rb
Created June 30, 2011 22:36
Base Converter gist
# This program shows various ways of writing 100
require 'base_converter'
bc = BaseConverter.new
(2..36).each do |num|
x = bc.dec_to_base(num,100)
puts "100 in base-#{num} is written as #{x}"
end
@rubydubee
rubydubee / assign4.rb
Created June 30, 2011 22:30
Assign 4
a, b = 5, 10
a, b = b/a, a-1 # => [2, 4]
a, b, c = 'A', 'B', 'C'
a, b, c = [a, b], { b => c }, a
puts a # => ["A", "B"]