Ruby Dynamically Naming Arrays

Ruby dynamically naming arrays

Ruby does not support dynamic local variable names1.

However, this can be easily represented using a Hash. A Hash maps a Key to a Value and, in this case, the Key represents a "name" and the Value is the Array:

# use Symbols for names, although Strings would work too
names = [:a, :b, :c]

# create a new hash
my_arrays = {}

# add some arrays to our hash
names.each_with_index { |name, index|
array = [index] * (index + 1)
my_arrays[name] = array
}

# see what we have
puts my_arrays

# access "by name"
puts my_arrays[:b]

(There are ways to write the above without side-effects, but this should be a start.)


1 Dynamic instance/class variable names are a different story, but are best left as an "advanced topic" for now and are not applicable to the current task. In the past (Ruby 1.8.x), eval could be used to alter local variable bindings, but this was never a "good" approach and does not work in newer versions.

Creating dynamic key names in Ruby hash?

You must remove the splat operator (*) in the method definition:

def Dictionary(dictionary, words)
word_count = Hash.new(0)
words.each do |word|
word_count[word] += 1 if dictionary.include?(word)
end
print word_count
end

Dictionary(dictionary, ["sit", "below"])
# {"sit"=>1, "below"=>1}

The reason is Ruby is wrapping the words argument within an array, which makes it be [["sit", "below"]] and when you iterate that, you get the value ["sit", "below"] as the only element, and hence the condition returns false.


As stated by NullUserException, the result isn't as expected. To do so you need to swap the array of words that's being iterated:

...
dictionary.each do |word|
word_count[word] += 1 if words.include?(word)
end
...

You could also take a look to the each_with_object method. It fits very well in this kind of cases:

dictionary.each_with_object(Hash.new(0)) do |word, hash|
next unless words.include?(word)

hash[word] += 1
end

Dynamically naming Arrays/Hashes in Ruby

You could do something like:

window = {}
5.times do |i|
window["my_new_array_#{i}"]=[]
end

Ruby dynamically create array

Assuming you're passing in a couple arrays of values and types, you can use the zip method to align them:

def info(values, types)
blocks = values.zip(types).map do |value, type|
{
'value' => value.to_i,
'type' => type
}
end

{
'individual' => {
'title' => 'Mr',
'firstName' => 'Joe',
'middleName' => '',
'lastName' => 'Bloggs',
'birthDate' => '2016-01-01',
'incomeAmount' => 50,
'emailAddress' => 'clear@gmail.com'

},
'blocks' => blocks
}
end

dynamically change method name inside array in ruby

With ActiveRecord you can access properties via the [] method:

[ :first_name, :email, :last_name ].each do |key|
unless (user[key])
puts "#{key} is required"
end
end

This generally a lot safer than the send approach because it's not calling arbitrary methods.

How to create dynamic array of hashes in Ruby on rails

You can try this

def array_of_hashes array
array.map{ |el| {id: el} }
end

and

array_of_hashes(["price", "tax"]) -> returns [{ id: "price" }, {id: "tax"}]


Related Topics



Leave a reply



Submit