How to use a recursive array - ruby

I have array, named a and define it with [1, 2, 3].
Next, I pushed it to itself:
a = [1, 2, 3]
a << a
and the result I get is:
#=> [1, 2, 3, [...]]
When I want to get the last element of array using a.last I get:
a.last
#=> [1, 2, 3, [...]]
#even
a.last.last.last
#=> [1, 2, 3, [...]]
What is going on, when we would push array to itself?
Yes, I understand that this should create a recursive array, but what can we do with it?

In Ruby variables, array elements etc. are object references. So when you do a = [1, 2, 3], there will be an array somewhere in memory and the a variable is a reference to that memory. Now when you do a << a, a[4] will also be a reference to that object. So in effect a now contains a reference to itself.

a = [1, 2, 3]
a << a.dup
a.last
=> [1, 2, 3]
a.last.last
=> 3
Maybe this is what you wanted. This just insert an array [1, 2, 3] as the last item of the a array. In the way you did you put a reference at the end of the a array and this becomes recursive.

Related

Ruby inject daisy chaining?

I'm not sure what sugar syntax this is, but let me just show you the problem.
def factors num
(1..num).select {|n| num % n == 0}
end
def mutual_factors(*nums)
nums
.map { |n| factors(n) }
.inject(:&)
end
p mutual_factors(50, 30) # [1, 2, 5, 10]
p mutual_factors(50, 30, 45, 105) # [1, 5]
p mutual_factors(8, 4) # [1, 2, 4]
p mutual_factors(8, 4, 10) # [1, 2]
p mutual_factors(12, 24) # [1, 2, 3, 4, 6, 12]
p mutual_factors(12, 24, 64) # [1, 2, 4]
p mutual_factors(22, 44) # [1, 2, 11, 22]
p mutual_factors(22, 44, 11) # [1, 11]
p mutual_factors(7) # [1, 7]
p mutual_factors(7, 9) # [1]
with this being the portion in questioning:
nums
.map { |n| factors(n) }
.inject(:&)
okay, so this is my mental trace: first, map uses the helper method to get the factors, and outputs the factors into another array, and then that array gets injected?
I think the
.inject(:&)
is what is throwing me off. I ran a quick google on it, but I haven't used inject for many things other than summing arrays, and basic stuff like that. I've also done things like
test = "hello".split("").map(&:upcase)
p test.join
but .inject(:&)? I know & is a proc, but I've only used them in arguments. I don't know the fundamentals under the hood. Please, take my current level into mind when trying to explain this to me =), I know how the basic inject works, and the splat operator also.
Partial quote form the documentation of Enumerable#inject.
inject(symbol) → object
[...]
Returns an object formed from operands via either:
A method named by symbol.
[...]
With method-name argument symbol, combines operands using the method:
# Sum, without initial_operand.
(1..4).inject(:+) # => 10
That means in the context of inject the (:&) is not a proc but simply the symbol :& that tells inject what operation to perform to combine the elements in the array.
Let's look at this example:
mutual_factors(8, 4, 10)
#=> [1, 2]
and let's look what happens at each step:
nums
.map { |n| factors(n) } #=> [[1, 2, 4, 8], [1, 2, 4], [1, 2, 5, 10]]
.inject(:&) #=> [1, 2, 4, 8] & [1, 2, 4] & [1, 2, 5, 10]
And Array#& is a method that returns a new array containing each element found in both arrays (duplicates are omitted).

Why a new call of a method with exclamation mark affects all previous calls of that method?

I'm sorry if this is a duplicate - I couldn't find anything similar in the existing posts.
I understand the difference between methods like shuffle and shuffle!. However, I am confused why calling the method more than once would result in changing the variables of all objects that previously referred to it? I'd expect once we apply a method, that the variable gets a value and we're done with it. Not that it continues to refer to the method call and the argument passed and that it would get re-evaluated later on.
I thought it's best to demonstrate with an example:
irb(main):001:1* def shuffle(arr)
irb(main):002:1* arr.shuffle!
irb(main):003:0> end
=> :shuffle
irb(main):004:0> arr = [1,2,3,4]
=> [1, 2, 3, 4]
irb(main):005:0> one = shuffle(arr)
=> [4, 2, 3, 1]
irb(main):006:0> two = shuffle(arr)
=> [1, 2, 4, 3]
irb(main):007:0> one
=> [1, 2, 4, 3]
So, here I'd expect one to stay [4, 2, 3, 1]. However, with each new call, all previous ones would get equated to the latest result of the method call. I realise it should have something to do with calling it with the same argument arr, but still doesn't quite make sense.
Array#shuffle! shuffles the array in-place and returns its receiver:
ary = [1, 2, 3, 4]
ary.equal?(ary.shuffle!) #=> true
Assigning the result from shuffle! to another variable doesn't change this. It merely results in two variables referring to the same array:
a = [1, 2, 3, 4]
b = a.shuffle!
a #=> [2, 4, 1, 3]
b #=> [2, 4, 1, 3]
a.equal?(b) #=> true
You probably want a new array. That's what Array#shuffle (without !) is for:
a = [1, 2, 3, 4]
b = a.shuffle
a #=> [1, 2, 3, 4]
b #=> [2, 4, 1, 3]
Even if shuffle returns the element in the original order, you'll get another array instance:
a = [1, 2, 3, 4]
b = a.shuffle until b == a
a #=> [1, 2, 3, 4]
b #=> [1, 2, 3, 4]
a.equal?(b) #=> false

What does Ruby block return to?

Good day. I've tried writing this code in ruby
x = [1, 2, 3, 4, 5]
x.each do |a|
a + 1
end
When I type this in irb, I don't understand why does it return
=> [1, 2, 3, 4, 5]
I thought it would return
=> [2, 3, 4, 5, 6] # because of a + 1
each yields the array's elements to the given block (one after another) without modifying the array. At the end, it returns the array, as mentioned in the docs:
[...] passes each successive array element to the block; returns self
You are probably looking for map, which works similar to each but instead of returning self, it ...
[...] returns a new Array whose elements are the return values from the block
Example:
x = [1, 2, 3, 4, 5]
x.map { |a| a + 1 }
#=> [2, 3, 4, 5, 6]
Note that it returns a new array without actually modifying x. There's also map! (with !) which does modify the receiver.

How can I get the next n number of elements using a Ruby enumerator?

I am trying to get the next n number of elements using a Ruby enumerator, with this:
a = [1, 2, 3, 4, 5, 6]
enum = a.each
enum.next(2) # expecting [1, 2]
enum.next(2) # expecting [3, 4]
But #next does not support that. Is there another way that I can do that?
Or shall I do?
What is the correct Ruby way to do that?
You can use take method
enum.take(2)
If you need slices of two elements, you could do:
e = enum.each_slice(2)
p e.next
#=> [1, 2]
p e.next
#=> [3, 4]
a = [1, 2, 3, 4, 5, 6]
enum = a.dup
enum.shift(2) # => [1, 2]
enum.shift(2) # => [3, 4]

How to insert an array in the middle of an array?

I have a Ruby array [1, 4]. I want to insert another array [2, 3] in the middle so that it becomes [1, 2, 3, 4]. I can achieve that with [1, 4].insert(1, [2, 3]).flatten, but is there a better way to do this?
You could do it the following way.
[1,4].insert(1,*[2,3])
The insert() method handles multiple parameters. Therefore you can convert your array to parameters with the splat operator *.
One form of the method Array#[]= takes two arguments, index and length. When the latter is zero and the rvalue is an array, the method inserts the elements of the rvalue into the receiver before the element at the given index (and returns the rvalue). Therefore, to insert the elements of:
b = [2,3]
into:
a = [1,4]
before the element at index 1 (4), we write:
a[1,0] = b
#=> [2,3]
a #=> [1,2,3,4]
Note:
a=[1,4]
a[0,0] = [2,3]
a #=> [2,3,1,4]
a=[1,4]
a[2,0] = [2,3]
a #=> [1,4,2,3]
a=[1,4]
a[4,0] = [2,3]
a #=> [1,4,nil,nil,2,3]]
which is why the insertion location is before the given index.
def insert_array receiver, pos, other
receiver.insert pos, *other
end
insert_array [1, 4], 1, [2, 3]
#⇒ [1, 2, 3, 4]
or, the above might be achieved by monkeypatching the Array class:
class Array
def insert_array pos, other
insert pos, *other
end
end
I believe, this is short enough notation to have any additional syntax sugar. BTW, flattening the result is not a good idea, since it will corrupt an input arrays, already having arrays inside:
[1, [4,5]].insert 1, *[2,3]
#⇒ [1, 2, 3, [4,5]]
but:
[1, [4,5]].insert(1, [2,3]).flatten
#⇒ [1, 2, 3, 4, 5]
My option without array#insert method
array = [1,2,3,6,7,8]
new_array = [4,5]
array[0...array.size/2] + new_array + array[array.size/2..-1]

Resources