Ruby String Naive Split because split is to clever

Problem

"aaa".split('a') == []
"aaa".split('a').join('a') == ""

Standard split is often ‘clever’, but not logical and not symmetric to join. To fix this here is a naive alternative that behaves ‘dumb’ but logical.

Solution

class String
  # https://grosser.it/2011/08/28/ruby-string-naive-split-because-split-is-to-clever/
  # "    ".split(' ') == []
  # "    ".naive_split(' ') == ['','','','']
  # "".split(' ') == []
  # "".naive_split(' ') == ['']
  def naive_split(pattern)
    pattern = /#{Regexp.escape(pattern)}/ unless pattern.is_a?(Regexp)
    result = split(pattern, -1)
    result.empty? ? [''] : result
  end
end

Ruby Hash leaves (leafs)

Get all leaves of a Hash (like recursive values).

Usage
{:x => 1, :y => {:z => 2}}.leaves == [1,2]

Code

class Hash
  # {'x'=>{'y'=>{'z'=>1,'a'=>2}}}.leaves == [1,2]
  def leaves
    leaves = []

    each_value do |value|
      value.is_a?(Hash) ? value.leaves.each{|l| leaves << l } : leaves << value
    end

    leaves
  end
end

Ruby Array.diff(other) difference between 2 Arrays

Diff is defined on Set, but not on Array, so we patch it in… (thanks to reto)
Usage
[1,2] ^ [2,3,4] == [1,3,4]

Code

class Array
  def ^(other)
    result = dup
    other.each{|e| result.include?(e) ? result.delete(e) : result.push(e) }
    result
  end unless method_defined?(:^)
  alias diff ^ unless method_defined?(:diff)
end

puts ([] ^ [1]).inspect          # [1]
puts ([1] ^ []).inspect          # [1]
puts ([1] ^ [2]).inspect         # [1,2]
puts ([] ^ []).inspect           # []
puts ([1,1] ^ [1,1,2,2]).inspect # [1]

The same could be done with (self | other) – (self & other) but would be less performant.

Installing MySql Handlersocket in Ubuntu Natty for Ruby

Install

sudo apt-get install mysql-server -y;
sudo apt-get install handlersocket-doc -y;
sudo apt-get install handlersocket-mysql-5.1 -y;
sudo apt-get install libhsclient-dev -y;

Configure

#/etc/mysql/my.cnf -- under mysqld section
loose_handlersocket_port = 9998
loose_handlersocket_port_wr = 9999
loose_handlersocket_threads = 16
loose_handlersocket_threads_wr = 1
open_files_limit = 65535 

Start

mysql -e "install plugin handlersocket soname 'handlersocket.so';"
sudo /etc/init.d/mysql restart

# should show lots of handlersocket processes
mysql -e "show processlist;"

Use

gem install handlersocket

require 'handlersocket'
h = HandlerSocket.new(:host => '127.0.0.1', :port => '9998')

# open PRIMARY index on widgets.user table, assign it ID #1
h.open_index(1, 'widgets', 'user', 'PRIMARY', 'user_name,user_email,created')
...

more of this can be found at ruby handlersocket introduction and ActiveRecord Handlersocket gem