Module: ActiveSupport::CoreExtensions::Hash::Join

Defined in:
lib/join.rb

Instance Method Summary collapse

Instance Method Details

#join(sep = $,) ⇒ Object

Returns a string created by converting each element of the hash to a string, separated by sep.

{ :a => :b, :c => :d }.join        #=> "abcd"
{ :a => :b, :c => :d }.join('-')   #=> "a-b-c-d"

If the hash has a key or value as a hash also, it’s also joined (just as it works with arrays).

{ :a => { :b => :c } }.join(' ')         #=> "a b c"

Note: hash order is just preserved in Ruby 1.9



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/join.rb', line 19

def join(sep = $,)
  array = []
  sep = sep.to_s

  self.each_pair do |k, v|
    array << (k.is_a?(Hash) ? k.join(sep) : k.to_s)
    array << (v.is_a?(Hash) ? v.join(sep) : v.to_s)
  end

  array.join(sep)
end