Saving an Element's Index to a Variable - ruby

I'm new to Ruby (and programming in general) and have been reading a ton of docs, how-tos and SO questions to try to find an answer to this problem but no luck so far.
I have an array of integers and I'm trying to save one of the object's integers to a variable to later delete that object from the array. What I have so far:
array = [3, 5, 1, 2, 6, 9]
objToDel = array[3]
array.delete_at(objToDel)
array
This deletes "1" in the array... I want it to delete "2" instead. I know this happens because having the variable point to array[3] points it to "2" instead of the actual third element in the array. I have tried the slice method as well to no avail.
So, is it possible to get a variable to equal an element's index instead of its content? Is this possible without turning the array into a hash?
Thanks in advance!

Sure, just assign the index to the variable:
index = 3
array.delete_at(index) # => 2
array # => [3, 5, 1, 6, 9]
You could also use the delete method to remove the object directly.
object_to_delete = 2
array.delete(object_to_delete) # => 2
array # => [3, 5, 1, 6, 9]
Note that this deletes all instances of the object in the array, which might not be what you want.

To keep it in your words, try this:
array = [3, 5, 1, 2, 6, 9]
objToDel = 3
array.delete_at(objToDel)
array
Good luck.

Related

Ruby variable behaviour when calling a method

I'm pretty good at getting answers from google, but I just don't get this. In the following code, why does variable 'b' get changed after calling 'addup'? I think I understand why 'a' gets changed (although its a bit fuzzy), but I want to save the original array 'a' into 'b', run the method on 'a' so I have two arrays with different content. What am I doing wrong?
Thanks in advance
def addup(arr)
i=0
while i< arr.length
if arr[i]>3
arr.delete_at(i)
end
i += 1
end
return arr
end
a = [1,2,3,4]
b = a
puts "a=#{a}" # => [1,2,3,4]
puts "b=#{b}" # => [1,2,3,4]
puts "addup=#{addup(a)}" # => [1,2,3]
puts "a=#{a}" # => [1,2,3]
puts "b=#{b}" # => [1,2,3]
Both a and b hold a reference to the same array object in memory. In order to save the original array in b, you'd need to copy the array.
a = [1,2,3,4] # => [1, 2, 3, 4]
b = a # => [1, 2, 3, 4]
c = a.dup # => [1, 2, 3, 4]
a.push 5 # => [1, 2, 3, 4, 5]
a # => [1, 2, 3, 4, 5]
b # => [1, 2, 3, 4, 5]
c # => [1, 2, 3, 4]
For more information on why this is happening, read Is Ruby pass by reference or by value?
but I want to save the original array 'a' into 'b'
You are not saving the original array into b. Value of a is a reference to an array. You are copying a reference, which still points to the same array. No matter which reference you use to mutate the array, the changes will be visible through both references, because, again, they point to the same array.
To get a copy of the array, you have to explicitly do that. For shallow arrays with primitive values, simple a.dup will suffice. For structures which are nested or contain references to complex objects, you likely need a deep copy. Something like this:
b = Marhal.load(Marshal.dump(a))
In the following code, why does variable 'b' get changed after calling 'addup'?
The variable doesn't get changed. It still references the exact same array it did before.
There are only two ways to change a variable in Ruby:
Assignment (foo = :bar)
Reflection (Binding#local_variable_set, Object#instance_variable_set, Module#class_variable_set, Module#const_set)
Neither of those is used here.
I think I understand why 'a' gets changed (although its a bit fuzzy)
a doesn't get changed either. It also still references the exact same array it did before. (Which, incidentally, is the same array that b references.)
The only thing which does change is the internal state of the array that is referenced by both a and b. So, if you really understand why the array referenced by a changes, then you also understand why the array referenced by b changes, since it is the same array. There is only one array in your code.
The immediate problem with your code is that, if you want a copy of the array, then you need to actually make a copy of the array. That's what Object#dup and Object#clone are for:
b = a.clone
Will fix your code.
BUT!
There are some other problems in your code. The main problem is mutation. If at all possible, you should avoid mutation (and side-effects in general, of which mutation is only one example) as much as possible and only use it when you really, REALLY have to. In particular, you should never mutate objects you don't own, and this means you should never mutate objects that were passed to you as arguments.
However, in your addup method, you mutate the array that is passed to you as arr. Mutation is the source of your problem, if you didn't mutate arr but instead returned a new array with the modifications you want, then you wouldn't have the problem in the first place. One way of not mutating the argument would be to move the cloneing into the method, but there is an even better way.
Another problem with your code is that you are using a loop. In Ruby, there is almost never a situation where a loop is the best solution. In fact, I would go so far as to argue that if you are using a loop, you are doing it wrong.
Loops are error-prone, hard to understand, hard to get right, and they depend on side-effects. A loop cannot work without side-effects, yet, we just said we want to avoid side-effects!
Case in point: your loop contains a serious bug. If I pass [1, 2, 3, 4, 5], the result will be [1, 2, 3, 5]. Why? Because of mutation and manual looping:
In the fourth iteration of the loop, at the beginning, the array looks like this:
[1, 2, 3, 4, 5]
# ↑
# i
After the call to delete_at(i), the array looks like this:
[1, 2, 3, 5]
# ↑
# i
Now, you increment i, so the situation looks like this:
[1, 2, 3, 5]
# ↑
# i
i is now greater than the length of the array, ergo, the loop ends, and the 5 never gets removed.
What you really want, is this:
def addup(arr)
arr.reject {|el| el > 3 }
end
a = [1, 2, 3, 4, 5]
b = a
puts "a=#{a}" # => [1, 2, 3, 4, 5]
puts "b=#{b}" # => [1, 2, 3, 4, 5]
puts "addup=#{addup(a)}" # => [1, 2, 3]
puts "a=#{a}" # => [1, 2, 3, 4, 5]
puts "b=#{b}" # => [1, 2, 3, 4, 5]
As you can see, nothing was mutated. addup simply returns the new array with the modifications you want. If you want to refer to that array later, you can assign it to a variable:
c = addup(a)
There is no need to manually fiddle with loop indices. There is no need to copy or clone anything. There is no "spooky action at a distance", as Albert Einstein called it. We fixed two bugs and removed 7 lines of code, simply by
avoiding mutation
avoiding loops

Clearing array without destructing the reference

I want to clear the array after declaring the hash value AND allow the hash value to remain intact.
Is that even possible?
hash = {}
number= "number"
array = [1,2,3,4,5,6]
hash[number]=array
This is the expected result, after clearing the array.
{"number"=>[1, 2, 3, 4, 5,6]}
hash[number] = array.dup
array.clear
hash
=> {"number"=>[1, 2, 3, 4, 5, 6]}
If your array contains just simple objects (as integers are), you can use dup method. Otherwise you need a deep copy.

How to achieve all elements swapped in an array

I have an ordered array which contain 1 to 1000000 elements.
I want to achieve an array such that the elements in the array are swapped with its next element.For instance if we assume the array elements are
[1,2,3,4,5,6]
I want to return an array with elements as
[2,1,4,3,6,5]
How do I achieve this in ruby for 100000 such elements? Can anyone guide me?
a = [1,2,3,4,5,6]
a.each_slice(2).map{|inner_a| inner_a.reverse}.flatten
# => [2, 1, 4, 3, 6, 5]
Description:
a.each_slice(2)returns an enumerator (#<Enumerator: [1, 2, 3, 4, 5, 6]:each_slice(2)>) with two element couples from your array. To see try a.each_slice(2).to_a. This returns [[1, 2], [3, 4], [5, 6]] with I only have to flatten for your expected result.
See also the first comment if you prefer a shorter notation of it.
Assuming you want to use a minimum amount of memory (since you chose a large array), and assuming the result is to be a mutated array (i.e. not a new array, but a change to the existing array) and finally assuming a is always an even number of elements...
a.each_index{|x| a[x], a[x+1] = a[x+1], a[x] if x.even?}
Possibly more performant...
(0...a.size).step(2) {|x| a[x], a[x+1] = a[x+1], a[x]}
You can try this.
arr = (1..100000).to_a
arr.each_with_index.each_slice(2){|(_,i), (_,j)| arr[i], arr[j] = arr[j], arr[i]}

Easiest way to SEARCH a Ruby array for a VALUE? (And delete specific array elements)

I'm a new Ruby programmer performing an exercise to make a program that lets people play fish. I'm building a method that will search for books and handle them when it finds them. I have my player hands stored in an array, so I want to search them for matches.
My 2 questions are:
What is the easiest, most effective and simplest way to search
through an array?
When I find 4 of a certain element in the same array, what is the
best way to delete those elements from the array?
I need to:
SEARCH the array for each element of %w(2 3 4 5 6 7 8 9 10 J Q K A)
#Values for cards, (I'm going to use a do each iterator for this, I got that). I need to know how to search the array in the first place.
Count each time I come across a match for the element
If count == 4, I have a book so I need to know how to delete specific elements of the array #(the 4 matching cards)
I know this is simple stuff, so thanks for the help and patience!
To search for elements in an array you can make use of select (alias find_all). Select will loop through and "select" elements that match conditions in the provided block, returning "selected" elements in an array.
Example:
['2', '3', '4'].select { |card| card == '2' } #=> ["2"]
You could also remove the need to search through an array by using a hash instead (mapping card values to the number of cards). This would allow you to easily check how many cards of a certain type a hand contains (see below for an example).
To count each time you come across an element you will need some data structure to store a card value and a count. A hash would be a good option here.
Example: card value => count
{ '2' => 1 }
To delete elements from an array you can use #delete or #delete_at to delete elements based on value or elements based on their array index. Another option is to use bang methods like #select! to transform your current array based on a provided block. Ruby has plenty of options for tasks like this.
I'd recommend skimming through methods for Array and Enumerable to get a better handle on what can be done with arrays. It's well worth your time as a lot of Ruby's power and elegance lies with Array and Enumerable.
http://www.ruby-doc.org/core-2.0.0/Array.html#method-i-select
http://ruby-doc.org/core-2.0.0/Enumerable.html#method-i-select
Best of luck!
Lots of overly complex answers.
Want to know if an element is in an array? Use include?.
[1, 2, 3, 4].include?(4) # true
[1, 2, 3, 4].include?(5) # false
Want to delete all instances of a value from an array? Use delete
x = [1, 2, 3, 4]
x.delete(4) # 4
x # [1, 2, 3]
y = [1, 1, 2, 2, 3, 3]
y.delete(4) # nil
y # [1, 1, 2, 2, 3, 3]
y.delete(2) # 2
y # [1, 1, 3, 3]
If you want to count the number of times a term appears, use count:
x = ['a', 'a', 'b', 'b', 'b']
x.count('a') # 2
x.count('b') # 3
You might want to have a look at enumerable module. There is pretty neat documentation here: http://ruby-doc.org/core-2.0.0/Enumerable.html My advise is to scan all the methods in this module as they are all extremely useful. For your task I would probably use count method. If you want to count all cards, group_by is what you want. Together with map you can do:
hand = [2,3,6,10,2,J,A,3,J,2,K,K,2]
Hash[hand.group_by{|value| value}.map{|key, values| [key, values.count]}]
# => {2 => 4, 3 => 2, 6 => 1, 10 => 1, J => 2, A => 1, K => 2}

Ruby extracting array values

I want to extract certain values from one array and concat them into another empty one:
freqs=[1,12,4,15,7,8,11,5,6]
less_freqs=[]
This is what I've come up with.
freqs.collect{|x| x<9 then x.to_a{|y|less_freqs<<y}}
Perhaps a different method? And, I'm not even sure if then makes any sense.
Is this what you're looking for?
freqs = [1,12,4,15,7,8,11,5,6]
less_freqs = freqs.select{|x| x < 9 } # => [1, 4, 7, 8, 5, 6]

Resources