get first value in hash within hash - ruby-on-rails

Is there a simple way, instead of looping my entire array to fetch the first value of every inner array.
so in essence I have the following;
array = [['test', 'test2'...], ['test' ....]]
so I want to grab array[#][0] and store the unqiue values.
EDIT
Is there a similar way to use the transpose method for arrays with Hash?
I essentially want to do the same thing
Hash = {1=> {1=> 'test', .....}, 2=> {1=> 'test',....}
so at the end I want to have something like new hash variable and leave my existing hash within hash alone.... = {1 => 'test', 2=> 'test2'}

Not sure if I fully understand the question, but if you have a 2 dimensional array (array in array), and you want to turn that into an array of the first element of the second dimension, you can use the map function
firsts = array.map {|array2| array2.first}
The way map works is that it turns one collection into a second collection by applying a function you provide (the block) to each element.

Maybe this?
array.transpose[0]

Related

Order array depending on appearance in another

Lets say I have 2 arrays of users.
[user1, user2, user3]
[user3]
Based on the second array, I want to sort the first array so that occurrences in the second array appear first in the first array.
So the result of the first array would be:
[user3, user1, user2]
I realise the simple way would be to iterate over the first array and populate an empty array, ordering it if the second array contains it, then merging the rest. The below is pseudo code and untested, but gives an idea of what I was thinking as a simple solution
return_array = []
array1.each do |a|
if array2.include? a
return_array.push array1.pop(a)
end
end
return_array.merge array1
Is there any way to refine this? Built in rails or ruby methods for example.
You should use array intersection and array difference:
a&b + a-b
would give you what you're looking for.
The manual for intersection: http://ruby-doc.org/core-2.2.0/Array.html#method-i-26
The manual for difference: http://ruby-doc.org/core-2.2.0/Array.html#method-i-2D
You could just do this:
array2 + (array1 - array2)
my_array = ['user1', 'user2', 'user3']
my_array2 = ['user3']
my_array2 + (my_array.sort - my_array2)

access values from multidimen array in ruby

Hi I have an array that i created using push like this
arr.push(h, s.power)
PS: h and s.power both are variables but depends on condition I applied
which ends up something like this
[22,"0.014",22,"0.01",22,"0.01",22,"0.082",22,"0.0002",22,"0.02822",22,"0.0042822",22,"0.041662",21,"0.0042822",21,"0.11107"]
but now I want to create new array for each new value like 22, 21 but I can not access it with many combinations I tried such as arr[22], with arr.map
You should consider using a Hash instead. See ruby hash documentation here.
So instead of pushing h and s.power into an array, you would add them to the hash like this:
my_hash[h] ||= []
my_hash[h].push(s.power)
The first line makes sure you have an array in the hash for the latest value of h. The second adds s.power to that array.
If you run this code repeatedly, you will end up with one array for each unique value of h which you can access like this:
my_hash[22] # <= returns the array of s.power values for h=22
my_hash[21] # <= returns the array of s.power values for h=21
If I understand your question correctly, this should be a clean way to do what you want.

Elegantly extracting all strings from an arbitrarily deep hash

My goal is to determine whether there is a blank in a hash like this:
{"departure_time_slots"=>{"date"=>[""], "time"=>{"start"=>[""], "end"=>[""]}}}
The strings are nested arbitrary times. I do not want to check each of them manually. It would be nice if I can extract all the strings regardless of their depth. Is there a simple way to do that?
Here's an example of how you can extract the values. However you will still have the problem of matching the values to the keys. You can't really have both at the same time.
# Extend the Hash class
class Hash
def recursive_values
self.values.collect { |v|
v.is_a?(Hash) ? v.recursive_values : v
}.flatten
end
end
Usage:
h = {"departure_time_slots"=>{"date"=>[""], "time"=>{"start"=>[""], "end"=>[""]}}}
h.recursive_values
=> ["", "", ""]
It will be better if you will use sth like that:
departure_time_slots = {:date => Time.new, :time_start => nil, :time_end => nil}
And when you use keys in Hash it is good practise to using Symbols for keys. (http://www.ruby-doc.org/core-1.9.3/Symbol.html)
No not possible. Because they are totally present in different scope with respect to each other.
For e.g.. keys start and end is totally unknown and masked from the departure_time_slots object in the example above.
One round abut way could be, getting all the values of the hashmap which are of type hashmap again and obtaining their keys recusively.
Fetch keys of departure_time_slots and then from the value list of that map, find all the keys from every value, if that were to be a hashmap. Other than that, I don't think there is another way.
P.S. On side note, see if u can modify your structure to an array where elements can also be arrays, and try and use flatten concept of arrays. :P

Passing an array of arrays from a form

I'm implementing a form based on Ryan Bate's [always excellent] Railscast, #52, Update Through Checkboxes, http://railscasts.com/episodes/52-update-through-checkboxes
In my case, I'm actually wanting to pass through an array of ids for each checkbox selected.
The key line in my form looks like this,
<td"><%= check_box_tag "sales_ids[]", batch["sales_ids"] %></td>
batch["sales_ids] itself is an array of ids, and the outcome I'm wanting is for an array of all the checked items (each representing an array of ids) to be passed along.
If I inspect the individual batch["sales_ids"] from the form, then I can confirm it is indeed an array, for example, [3907, 3908, 3909] (remember, I want to pass along an array of these items for each row checked)
The key line from the method that handles the form looks like this,
params[:sales_ids].each { |batch| Sales.update_all(["code=?", 99], :id => batch) }
The intent of this code, again based on the Railscast example, is to iterate over the array of arrays, and update each sub-array of ids.
When I examine the received array, I see, ["5412", "3907 3908 3909", "2452"]
The sub-array isn't handled as an array and (for reasons I don't understand) only the first item each 'substring' (in this case "5412", "3907", "2452") is updated.
It seems that the passed subarray isn't actually an array, or something else is awry.
I'd appreciate help in how to pass and receive these ids as an array of arrays. Thanks.
as far as I know, passing arrays of arrays in this way won't work via a form. However there is a work around that should work fine for you.
in the view do this for your checkboxes: (I'm assuming batch["sales_ids"] is an array)
<%= check_box_tag "sales_ids[]", batch["sales_ids"].join(",") %>
And in your controller do this:
params[:sales_ids].collect{|a| a.split(",") }.each { |batch| Sales.update_all(["code=?", 99], :id => batch) }
Instead of passing an array of arrays, we are now passing an array of comma separated values. In the controller these comma separated values are turned into an array.

What's the difference between arrays and hashes?

What's the difference between arrays and hashes in Ruby?
From Ruby-Doc:
Arrays are ordered, integer-indexed collections of any object. Array indexing starts at 0, as in C or Java. A negative index is assumed to be relative to the end of the array—that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on. Look here for more.
A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. Hashes enumerate their values in the order that the corresponding keys were inserted.
Hashes have a default value that is returned when accessing keys that do not exist in the hash. By default, that value is nil. Look here for more.
Arrays:
Arrays are used to store collections of data. Each object in an array has an unique key assigned to it. We can access any object in the array using this unique key. The positions in an array starts from " 0 ". The first element is located at " 0 ", the second at 1st position etc.
Example:
Try the following in - irb.
bikes = Array.new
bikes = %w[Bajaj-Pulsar, Honda-Unicorn, TVS-Apache, Yamaha, Suzuki]
You have added 4 elements in the array.
puts bikes[3]
Yamaha,
Add a new element to position 5.
bikes[5] = "Hardly Davidson"
Hashes:
Like arrays, Hashes are also used to store data. Hashes points an object to another object. Consider of assigning a certain "meaning" to a string. Each time you refer that string, it refers its "meaning".
Example:
bikes = Hash.new
bikes = {
'Bajaj' => 'Pulsar 220, Pulsar 200, Pulsar 180 and Pulsar 150',
'Honda' => 'Unicorn, Shine and Splendor',
'TVS' => 'Apache, Star City, and Victor'
}
Try this now:
bikes['Bajaj']
You get => "Pulsar 220, Pulsar 200, Pulsar 180 and Pulsar 150"
An array is an ordered list of things: a, b, c, d
A hash is a collection of key/value pairs: john has a peugeot, bob has a renault, adam has a ford.
The two terms get "hashed" together these days. I think this is how it goes:
A "hash" will have key -> value pairs:
(top -> tshirt, bottom -> shorts, feet -> shoes)
And an "array" will typically have an index:
([0]tshirt, [1]shorts, [2]shoes)
But, right or wrong, you'll see things with key -> value pairs called "arrays", too.
I think the difference depends mainly on when and how you want to use them. You won't get into much trouble calling an array a hash, or vice versa, but you should know the difference.

Resources