How to replace a hash key with another key
hash[:new_key] = hash.delete :old_key
Update hash values with hash key
I am posting another answer now since I realize what the question is all about.
Use Iteraptor
gem:
require 'iteraptor'
require 'yaml'
# or load from file
yaml = <<-YAML.squish
api: 'active'
server:
test:
user: 'test'
password: 'passwordfortest'
prod:
user: 'nottest'
password: 'morecomplicatedthantest'
YAML
mapped =
yaml.iteraptor.map(full_parent: true) do |parent, (k, _)|
v = parent.map(&:capitalize).join('.')
[k, "\#{#{v}}"]
end
puts YAML.dump(mapped)
#⇒ ---
# api: "#{Api}"
# server:
# test:
# user: "#{Server.Test.User}"
# password: "#{Server.Test.Password}"
# prod:
# user: "#{Server.Prod.User}"
# password: "#{Server.Prod.Password}"
puts YAML.dump(mapped).delete('"')
#⇒ ---
# api: #{Api}
# server:
# test:
# user: #{Server.Test.User}
# password: #{Server.Test.Password}
# prod:
# user: #{Server.Prod.User}
# password: #{Server.Prod.Password}
Working with Hashes that have a default value
0 will be the fallback if you try to access a key in the hash that doesn't exist
For example:
count = Hash.new
-> count['key'] => nil
vs
count = Hash.new(0)
-> count['key'] => 0
Is there any difference between the `:key = value` and `key: value` hash notations?
Yes, there is a difference. These are legal:
h = { :$in => array }
h = { :'a.b' => 'c' }
h[:s] = 42
but these are not:
h = { $in: array }
h = { 'a.b': 'c' } # but this is okay in Ruby2.2+
h[s:] = 42
You can also use anything as a key with =>
so you can do this:
h = { C.new => 11 }
h = { 23 => 'pancakes house?' }
but you can't do this:
h = { C.new: 11 }
h = { 23: 'pancakes house?' }
The JavaScript style (key: value
) is only useful if all of your Hash keys are "simple" symbols (more or less something that matches /\A[a-z_]\w*\z/i
, AFAIK the parser uses its label pattern for these keys).
The :$in
style symbols show up a fair bit when using MongoDB so you'll end up mixing Hash styles if you use MongoDB. And, if you ever work with specific keys of Hashes (h[:k]
) rather than just whole hashes (h = { ... }
), you'll still have to use the colon-first style for symbols; you'll also have to use the leading-colon style for symbols that you use outside of Hashes. I prefer to be consistent so I don't bother with the JavaScript style at all.
Some of the problems with the JavaScript-style have been fixed in Ruby 2.2. You can now use quotes if you have symbols that aren't valid labels, for example:
h = { 'where is': 'pancakes house?', '$set': { a: 11 } }
But you still need the hashrocket if your keys are not symbols.
Ruby - how to add an array to a hash key?
car_data['NEW']
has to be declared as Array
.
car_data = Hash.new
car_data['NEW'] = []
Car.all.each do |c|
car_data[c.brand] = c.id
car_data['NEW'] << c.id if c.new == 1
end
You can also do it in a single step
car_data = { new: [] }
Car.all.each do |c|
car_data[c.brand] = c.id
car_data[:new] << c.id if c.new == 1
end
Frankly, it seems a little bit odd to me to use a Hash in that way. In particular, mixin different kind of information in Hash is a very bad approach inherited from other non object oriented languages.
I'd use at least two separate variables. But I don't know enough about the context to provide a meaningful example.
Ruby array to hash: each element the key and derive value from it
Ruby's each_with_object
method is a neat way of doing what you want
['a', 'b'].each_with_object({}) { |k, h| h[k] = k.upcase }
How to remove a key from Hash and get the remaining hash in Ruby/Rails?
Rails has an except/except! method that returns the hash with those keys removed. If you're already using Rails, there's no sense in creating your own version of this.
class Hash
# Returns a hash that includes everything but the given keys.
# hash = { a: true, b: false, c: nil}
# hash.except(:c) # => { a: true, b: false}
# hash # => { a: true, b: false, c: nil}
#
# This is useful for limiting a set of parameters to everything but a few known toggles:
# @person.update(params[:person].except(:admin))
def except(*keys)
dup.except!(*keys)
end
# Replaces the hash without the given keys.
# hash = { a: true, b: false, c: nil}
# hash.except!(:c) # => { a: true, b: false}
# hash # => { a: true, b: false }
def except!(*keys)
keys.each { |key| delete(key) }
self
end
end
Hash key access via symbol not string
Because 'key'
is a String
and :key
is a Symbol
- those are two different things in Ruby.
It can be somewhat confusing, because :'key'
, or 'key':
will also be a Symbol
To make it work, just access Hash
fields with a Symbol
, like:
if (auth[:user])
To convert String indexed Hash to Symbol indexed Hash, refer to this question:
Best way to convert strings to symbols in hash
Related Topics
How to Ruby on Rails Authentication with Ldap
How to Programmatically Generate Heroku-Like Subdomain Names
Ruby Method Calls Declared in Class Body
Finding Nil Has_One Associations in Where Query
How to Select Option in Drop Down Using Capybara
Ruby JSON Parse Changes Hash Keys
Convert String to Specific Datetime Format
Ruby Way to Check for String Palindrome
How to Convert Nokogiri Document Object into JSON
How to Set Up a Sinatra App Under Apache with Passenger
How to Remove Carriage Returns with Ruby
Rails: How to Access Restful Helpers
Split Ruby Regex Over Multiple Lines
How to Describe an Enumeration Column in a Rails 3 Migration
Calling Method in Parent Class from Subclass Methods in Ruby