Performance of Arrays and Hashes in Ruby

Hashes are much faster for lookups: require ‘benchmark’ Document =,:a,:b,:c) documents_a = [] documents_h = {} 1.upto(10_000) do |n| d = documents_a << d documents_h[] = d end searchlist ={ rand(10_000)+1 } do |x|‘array’){searchlist.each{|el| documents_a.any?{|d| == el}} }‘hash’){searchlist.each{|el| documents_h.has_key?(el)} } end # user system total real #array 2.240000 … Read more

Installing Nokogiri on OSX 10.10 Yosemite

I managed to install Nokogiri under Yosemite (OS X 10.10 Preview). Step 1: Install Brew Skip this if brew was installed. ruby -e “$(curl -fsSL” Step 2: Install brew libs brew tap homebrew/dupes brew install libxml2 libxslt brew install libiconv Step 3: Download and install Apple Commandline Tools for 10.10 It’s important that you … Read more

How to get rid of non-ascii characters in ruby

Use String#encode The official way to convert between string encodings as of Ruby 1.9 is to use String#encode. To simply remove non-ASCII characters, you could do this: some_ascii = “abc” some_unicode = “áëëçüñżλφθΩ𠜎😸” more_ascii = “123ABC” invalid_byte = “\255” non_ascii_string = [some_ascii, some_unicode, more_ascii, invalid_byte].join # See String#encode documentation encoding_options = { :invalid => :replace, … Read more

DRY Ruby Initialization with Hash Argument

You don’t need the constant, but I don’t think you can eliminate symbol-to-string: class Example attr_reader :name, :age def initialize args args.each do |k,v| instance_variable_set(“@#{k}”, v) unless v.nil? end end end #=> nil e1 = :name => ‘foo’, :age => 33 #=> #<Example:0x3f9a1c @name=”foo”, @age=33> e2 = :name => ‘bar’ #=> #<Example:0x3eb15c @name=”bar”> … Read more

How do you downgrade rubygems?

This worked for me when downgrading from 1.5.2 to 1.4.2 because of old rails version: sudo gem update –system 1.4.2 More information about downgrading/upgrading rubygems: