#!/usr/bin/env ruby class Object def symbolize; self; end end class String def symbolize; match(/\A\w+\z/) ? to_sym : self; end end class Array def symbolize; map { |e| e.symbolize }; end end class Hash def symbolize inject({}) do |hash, (attribute, value)| hash[attribute.symbolize] = value.symbolize hash end end end if __FILE__ == $0 require 'test/unit' class TestSymbolize < Test::Unit::TestCase def test_integer_symbolize assert_equal(1, 1.symbolize) end def test_string_symbolize assert_equal(:expected, "expected".symbolize) end def test_array_symbolize array = ('a'..'d').to_a expected = array.map { |e| e.to_sym } assert_equal(expected, array.symbolize) end def test_hash_symbolize hash = {'a' => 'x', 'b' => 'y', 'c' => 'z'} expected = hash.inject({}) { |h, (a, v)| h[a.to_sym] = v.to_sym; h } assert_equal(expected, hash.symbolize) end def test_array_with_non_word_element assert_equal([:a, :b, :c, 'x x'], ['a', 'b', 'c', 'x x'].symbolize) end def test_hash_with_non_word_strings assert_equal( {:a => :x, :b => :y, :c => 'a b', 'x x' => :c}, { 'a' => 'x', 'b' => 'y', 'c' => 'a b', 'x x' => 'c' }.symbolize ) end def test_hash_with_array_inside assert_equal( {:a => :x, :b => [ :c, :d, 'x x']}, {'a' => 'x', 'b' => [ 'c', 'd', 'x x']}.symbolize ) end def test_array_with_hash_inside assert_equal( [:a , { :b => :c, :d => 'x x'}], ['a' , { 'b' => 'c', 'd' => 'x x'}].symbolize ) end end end