coding, ruby

Map Reduce plus filter using Ruby

Previous two articles were dedicated to JavaScript and map reduce and filtering of somewhat large data, elegance of code, etc.

Going forward, i’d like to evaluate other languages doing the same exact thing.

And i’m curious about performance too.


Here is my version of the same code i wrote but in Ruby (Ruby 2.1.1 was used). Didn’t even run in Jruby 1.7 unfortunately.


 class Time
 	def to_ms
 		(self.to_f * 1000.0).to_i

 total = 300 *10000
 data =

 total.times.each {|x|
 	data.push({name: 'it', salary: 33*x})

 data.push({name: "it", salary: 100})
 data.push({name: "acc", salary: 100})

 def self.timeMe
 	start =
 	endtime =
 	puts "Time elapsed #{endtime - start} ms"

 timeMe do
 	boom = {|j|  j[:salary] if j[:name] =='it' }.compact.reduce(:+)
 	puts "and  boom: #{boom} "



and  boom: 148499950500100
Time elapsed 1194 ms

Not bad but not as fast as javascript, probably due to array containing Hash, as opposed to one of the core types in javascript (a simple object) .

I’m not entirely sure why Jruby didn’t run, id love to learn.

Update (2014/april 18): Java 1.6 with JVM parameters (needed) posted results of around 600ms , JVM 1.8 didn’t seem to work at the moment.

On another note, Ruby’s syntax is simply lovely {|j|  j[:salary] if j[:name] =='it' }.compact.reduce(:+)


Share This:

coding, ruby

Ruby interview challenge

I had a pleasure of getting an interview with an upcoming startup (i won’t disclose which one). Besides implementing fizz buzz in ruby, i was asked to write a method that would check for input to be a palindrome.

Palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or backward.

Keep in mind: using reverse is not allowed 🙂

I wrote two versions since i wasn’t pleased with my first one.


Rspec – testing driven development

require 'spec_helper'
require 'blah'

describe "Blah" do 

	it "should match reversed order of the word " do
		palindrome("abba").should == true
		palindrome("abcba").should == true
	it "should reject if reversed order doesnt match" do 
		palindrome("abbac").should_not == true

	it "should handle empty string with passing" do 
		palindrome("").should == true

	it "should handle various cases " do
		palindrome("AbbA").should == true

	it "should handle empty spaces " do
		palindrome("   Ab  bA").should == true


Version 1

def palindrome2(word)

i = 0
last = -1
word.each_char do |c|
	if word[i] != word[last]
		return false
	last -=1

return true



Version 2

def palindrome(word)
	word = word.downcase.gsub(" ","").chars 
	word.each{|c| return false if  word.shift != word.pop  }

I have a feeling there is a better way of writing this.


Share This: