I need to add an array of array in to a single array without duplicates
array = [[1,2,3],[2,3,4],[7,8,9]]
to
new_array [1,2,3,4,7,8,9]
What is the best possible way to do IT in Ruby.
Try this:
array.flatten!.uniq!
flatten! takes any sub-arrays and adds their elements to the enclosing array (recursively), so it "flattens out" arrays of arrays.
uniq! removes duplicate elements from the array.
Note that ! methods modify the original array. Use the non-! methods (flatten and uniq) if you wish to return a new array instead.
Related
Persoane = []
Nume = gets
Persoane.push Nume.split(",")
puts Persoane.sort
I am trying to get an user to input carachters that get split into substrings which get inserted in an array, then the program would output the strings in alphabetical order. It doesnt seem to work and I just get the array's contents, like so:
PS C:\Users\Lenovo\Desktop\Ruby> ruby "c:\Users\Lenovo\Desktop\Ruby\ruby-test.rb"
Scrie numele la persoane
Andrei,Codrin,Bradea
Andrei
Codrin
Bradea
PS C:\Users\Lenovo\Desktop\Ruby>
you can do this :
Nume = gets
puts Nume.split(",").sort
or in 1 line
array = gets.chomp.split(",").sort
The error is because of your use of push. Let's assume that you define the constant Nume by
Nume='Andrei,Codrin,Bradea'
Then, Nume.split(',') would return the Array ['Andrei', 'Codrin', 'Bradea']. When you do a Persoane.push, the whole array is added to your array Persoane as a single element. Therefore, Persoane contains only one Element, as you can verify when you do a
p Persoane
If you sort a one-element array, the result will also be just that one element - there is nothing to sort.
What you can do is using concat instead of push. This would result in Persoane being a 3-element array which can be sorted.
I'm not sure you need use constants here
If you don't need keep user input and use it somewhere, you can just chain methods like this
persons = gets.chomp.split(",").sort
For something a little different, let's not split at all.
people = gets.scan(/[^,]+/).map(&:strip).sort
This will avoid problems like multiple commas in a row yielding empty strings. Of course, you could also avoid that with:
people = gets.split(/\,+/).map(&:strip).sort
I am currently trying to compare every element of an array with the others (in Ruby). Those elements are objects of a class. I need to find similarities between them. My idea was to loop through the original array and in this loop creating a new array containing the other elements (not the one of the outer loop) and then loop through this second array and compare every item with the one in the outer each loop.
Here is some pseudocode:
originalArray.each{
|origElement|
tempArray = createNewArray from original array without origElement
tempArray.each{
|differentElement|
Compare origElement with differentElement
}
}
How can I create that tempArray?
I think you should use Array#permutation for this
original_array.permutation(2) { |elements| Compare elements[0] with elements[1] }
First, I want to say bjhaid's answer is beautiful and for your specific instance, it is the one that should be used.
However, I wanted to provide a more general answer that answers the direct question you asked: "How can I create that tempArray?"
If you wanted to delete all values that are equal to the element in the original array, you could simply do:
tempArray = originalArray - [origElement]
However, if you only want to delete that element, you could do:
originalArray.each_with_index {
|origElement, index|
tempArray = originalArray.dup
tempArray.delete_at(index)
tempArray.each{
|differentElement|
Compare origElement with differentElement
}
}
Also, a note on styling. You probably want to use underscores instead of CamelCase for all methods/variables. In the Ruby community, CamelCase is typically reserved for class / module names. You also probably want to keep the "piped-in" variables (called block arguments) on the same line as the beginning of the block. It is certainly not a requirement, but it is an almost universal convention in the Ruby community.
This code snippet would be much more familiar and readable to your typical Ruby dev:
original_array.each_with_index do |orig_element, index|
temp_array = original_array.dup
temp_array.delete_at(index)
temp_array.each do |different_element|
Compare orig_element with different_element
end
end
I have a method which returns the number of hotels from a webpage:
hotel_count = self.getHotelsList.values
The output of this method is:
[["hotel_0", "hotel_1", "hotel_2", "hotel_3", "hotel_4", "hotel_5", "hotel_6", "hotel_7", "hotel_8", "hotel_9", "hotel_10", "hotel_11", "hotel_12", "hotel_13", "hotel_14", "hotel_15", "hotel_16", "hotel_17", "hotel_18", "hotel_19", "hotel_20", "hotel_21", "hotel_22", "hotel_23", "hotel_24", "hotel_25", "hotel_26", "hotel_27", "hotel_28", "hotel_29", "hotel_30", "hotel_31", "hotel_32", "hotel_33", "hotel_34", "hotel_35", "hotel_36", "hotel_37", "hotel_38", "hotel_39", "hotel_40"]]
I want to know the length of this array, but if I write
hotel_count = self.getHotelsList.values.length
The length is 1. How can I get a length of 41, which is the one I'm expecting?
Thanks
The array you are showing is nested inside another array. So the outer array is of length 1, the inner array is what you want.
To get it you have to first get the first element of the outer array using [0] or first
testList[0].length
testList.first.length
I am not sure why your getHotelsList method returns a nested array, it doesn't appear to need it.
hotel_count = getHotelsList.values.first.length
You can also do it with [0], but first is faster.
Two notes:
You don't need self at the beginning.
It is a bad habit to use camel case for method names in Ruby. it should better be get_hotels_list.
You could convert that into a single array with flatten:
hotel_count = self.getHotelsList.values.flatten.size
I am iterating on a array within a Object van. I am trying to pop the elements of the array into another object array. See below.
#van.bikes.each { #garage<<( #van.removebike )}
def removebike
#bikes.pop
end
When I do this the resulting array in the garage has missing elements and/or duplicate elements.
The reason for this is that when ruby iterates on the array it sets number of iterations based on the original array size. When you pop an element from that array the size changes so the iteration can not work properly.
You can use instead,
#van.bikes.count.times { #garage<<( #van.removebike )}
You can try this too..
#garage = []
#van.bikes.each{|bike| #garage << bike}
I have a couple of arrays that I want to put nils into so that my indexing will
be further into the array based on how I use the aray. Is there a faster, more efficient and elegant way ?
(1..#epgroup_overide_count.to_i).each do
#grp['Overides'].unshift(nil)
#grp['channel_overides'].unshift(nil)
end
#unshift takes a splatted arg list to prepend multiple elements, so:
#group['Overides'].unshift(*([nil]*#epgroup_override_count.to_i))
This will do it (similar for your second one)
Breaking down the one liner:
[nil] * #epgroup_override_count.to_i
Multiplying an array by a number duplicates the array that many times, but as a single flat array ([1,2,3]*3 #=> [1,2,3,1,2,3,1,2,3]). One thing to be aware of is that if the array has variable references, it creates multiple references to the same objects, not duplicates.
*(above_multiplied_array)
using the splat operator to spread the array into the args of the method
arr.unshift(multiple, args, here)
By using the splat operator, we spread the array into multiple args to #unshift. When #unshift is given multiple args, it prepends all of them to the array, which is the desired result.
You can do like below:
#grp['Overides'] +=([nil]*#epgroup_override_count.to_i).flatten
#grp['channel_overides'] += ([nil]*#epgroup_override_count.to_i).flatten
or
nil_array = ([nil]*#epgroup_override_count.to_i).flatten
#grp['Overides'] += nil_array
#grp['channel_overides'] += nil_array