Built in way of doing successive Ruby evals on the same object - ruby

Edit: I just realized my prior example was bad.
Borrowing #ZachKemp's idea (and changing it):
class Object
def eval_multi(*methods)
#methods.inject(self) { |memo, m| memo.send(m) }
methods.inject(self) { |memo, m| eval("#{memo}.#{m}") }
end
end
[1,2,3].eval_multi("product([4,5,6])", :transpose)
=> [[1, 1, 1, 2, 2, 2, 3, 3, 3], [4, 5, 6, 4, 5, 6, 4, 5, 6]]
I'm wondering if there's a built-in way of doing this without having to write the eval_multi method above.

You can do this with inject:
module Enumerable
def multimap(*methods)
methods.inject(self){|result, method| result.map(&method) }
end
end
arr = ["1 a", "1 b", "2 c", "2 a"]
arr.multimap(:split, :reverse, :join)
#=> ["a1", "b1", "c2", "a2"]
(I renamed the method because eval already has another meaning in Ruby).

You could just use one map, simple and clean.
arr.map{ |o| o.split.reverse.join }

You can do it with a little change in the way you pass the arguments.
[[:product, [4,5,6]], [:transpose]].inject([1,2,3]){|m, a| m.send(*a)}
# => [[1, 1, 1, 2, 2, 2, 3, 3, 3], [4, 5, 6, 4, 5, 6, 4, 5, 6]]
Or, by modifying send a little bit, you can do it like this:
class Object
def send_splat a; send(*a) end
end
[[:product, [4,5,6]], [:transpose]].inject([1,2,3], &:send_splat)
# => [[1, 1, 1, 2, 2, 2, 3, 3, 3], [4, 5, 6, 4, 5, 6, 4, 5, 6]]

Related

Getting different output from manual vs. programmatic arrays

I’m getting some weird results implementing cyclic permutation on the children of a multidimensional array.
When I manually define the array e.g.
arr = [
[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]
]
the output is different from when I obtain that same array by calling a method that builds it.
I’ve compared the manual array to the generated version and they’re exactly the same (class and values, etc).
I tried writing the same algorithm in JS and encountered the same issue.
Any idea what might be going on?
def Build_array(child_arr, n)
#Creates larger array with arr as element, n times over. For example Build_array([1,2,3], 3) returns [[1,2,3], [1,2,3], [1,2,3]]
parent_arr = Array.new(4)
0.upto(n) do |i|
parent_arr[i] = child_arr
end
return parent_arr
end
def Cylce_child(arr, steps_tocycle)
# example: Cylce_child([1, 2, 3, 4, 5], 2) returns [4, 5, 1, 2, 3]
0.upto(steps_tocycle - 1) do |i|
x = arr.pop()
arr.unshift(x)
end
return arr
end
def Permute_array(parent_array, x, y, z)
#x, y, z = number of steps to cycle each child array
parent_array[0] = Cylce_child(parent_array[0], x)
parent_array[1] = Cylce_child(parent_array[1], y)
parent_array[2] = Cylce_child(parent_array[2], z)
return parent_array
end
arr = Build_array([1, 2, 3, 4, 5], 4)
# arr = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
puts "#{Permute_array(arr, 1, 2, 3)}"
# Line 34: When arr = Build_array([1, 2, 3, 4, 5], 4)
# Result (WRONG):
# [[5, 1, 2, 3, 4], [5, 1, 2, 3, 4], [5, 1, 2, 3, 4], [5, 1, 2, 3, 4]]
#
# Line 5: When arr = [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, # 2, 3, 4, 5]]
# Result (CORRECT):
# [[5, 1, 2, 3, 4], [4, 5, 1, 2, 3], [3, 4, 5, 1, 2], [1, 2, 3, 4, 5]]
#
The problem is in the way you build the array.
This line:
parent_arr[i] = child_arr
does not put in parent_arr[i] a copy of child_arr but a reference to it.
This means your initial array contains four references to the same child array. Later on, when the code changes parent_arr[0], it changes the same array that child_arr was referring to in the build method. And that array is also parent_arr[1] and parrent_arr[2] and so on.
A simple solution to the problem is to put in parent_arr[i] a copy of child_arr:
parent_arr[i] = Array.new(child_arr)
I see where the bug was. Added the clone method to line 8 so that it now reads:
parent_arr[i] = child_arr.clone
#Old: parent_arr[i] = child_arr
Thanks Robin, for pointing me in the right direction.
This is a fairly common mistake to make in Ruby since arrays do not contain objects per-se, but object references, which are effectively pointers to a dynamically allocated object, not the object itself.
That means this code:
Array.new(4, [ ])
Will yield an array containing four identical references to the same object, that object being the second argument.
To see what happens:
Array.new(4, [ ]).map(&:object_id)
# => => [70127689565700, 70127689565700, 70127689565700, 70127689565700]
Notice four identical object IDs. All the more obvious if you call uniq on that.
To fix this you must supply a block that yields a different object each time:
Array.new(4) { [ ] }.map(&:object_id)
# => => [70127689538260, 70127689538240, 70127689538220, 70127689538200]
Now adding to one element does not impact the others.
That being said, there's a lot of issues in your code that can be resolved by employing Ruby as it was intended (e.g. more "idiomatic" code):
def build_array(child_arr, n)
# Duplicate the object given each time to avoid referencing the same thing
# N times. Each `dup` object is independent.
Array.new(4) do
child_arr.dup
end
end
def cycle_child(arr, steps_tocycle)
# Ruby has a rotate method built-in
arr.rotate(steps_tocycle)
end
# Using varargs (*args) you can just loop over how many positions were given dynamically
def permute_array(parent_array, *args)
# Zip is great for working with two arrays in parallel, they get "zippered" together.
# Also map is what you use for transforming one array into another in a 1:1 mapping
args.zip(parent_array).map do |a, p|
# Rotate each element the right number of positions
cycle_child(p, -a)
end
end
arr = build_array([1, 2, 3, 4, 5], 4)
# => [[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]
puts "#{permute_array(arr, 1, 2, 3)}"
# => [[5, 1, 2, 3, 4], [4, 5, 1, 2, 3], [3, 4, 5, 1, 2]]
A lot of these methods boil down to some very simple Ruby so they're not especially useful now, but this adapts the code as directly as possible for educational purposes.

Split an array into arrays

I'm new to Ruby and would like to know if there is a better way to solve the following problem.
I have an array that looks like this:
[6, 1, 3, 6, 2, 4, 1, 3, 2, 3]
I'd like to turn it into this:
[ [1,1], [2,2], [3,3,3], [4], [], [6,6] ]
This is my current solution (again, I'm new to Ruby):
def split_array_into_arrays(array)
max_num = array.max
arrays = Array.new(max_num) { Array.new }
array.each do |num|
arrays[num-1] << num
end
arrays
end
arrays = split_array_into_arrays([6, 1, 3, 6, 2, 4, 1, 3, 2, 3])
puts arrays.inspect
Produces:
[[1, 1], [2, 2], [3, 3, 3], [4], [], [6, 6]]
Note: I realize I am not handling possible errors.
How might an experienced Ruby developer implement this?
ar = [6, 1, 3, 6, 2, 4, 1, 3, 2, 3]
(1..ar.max).map{|n| [n]*ar.count(n)}
# => [[1, 1], [2, 2], [3, 3, 3], [4], [], [6, 6]]

Ruby, perform operation on an array and return the new array, aswell as "changes"

I am looking for a way to perform a certain operation (for instance delete_if) on an array and return both the deleted elements, and the remaining elements.
For example
a = [1,2,3,4,5,6,7,8,9,10]
a.delete_if {|x| x.even? } #=> [[1, 3, 5, 7, 9]]
But what I am looking for is something like
a = [1,2,3,4,5,6,7,8,9,10]
a.some_operation #=> [[1,3,5,7,9],[2,4,6,8,10]]
How would I go about doing this?
Using Enumerable#partition:
a = [1,2,3,4,5,6,7,8,9,10]
a.partition &:even?
# => [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
The first element of the Enumerable#partition return value contains the elements that are evaluated to true in the block. So you need to use odd? to get what you want.
a.partition &:odd?
# => [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]
You might be looking for something like this:
a = [1,2,3,4,5,6,7,8,9,10]
a.group_by { |x| x.even? }.values
#=> [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]

How can I split an array by delimiters in Ruby?

For example, if I have an array like this:
[:open, 1, :open, 2, 3, :close, 4, :close, :open, 5, :close]
I want to get this:
[[1, [2, 3], 4], [5]]
The :open effectively becomes [ and :close becomes ]
You could probably do this with a stack, but it's pretty easy to design recursively:
#!/usr/bin/env ruby
x = [:open, 1, :open, 2, 3, :close, 4, :close, :open, 5, :close]
def parse(list)
result = []
while list.any?
case (item = list.shift)
when :open
result.push(parse(list))
when :close
return result
else
result.push(item)
end
end
return result
end
puts parse(x).inspect
Note that this will destroy your original array. You should clone it before passing it in if you want to preserve it.
ar = [:open, 1, :open, 2, 3, :close, 4, :close, :open, 5, :close]
p eval(ar.inspect.gsub!(':open,', '[').gsub!(', :close', ']'))
#=> [[1, [2, 3], 4], [5]]
The same to steenslag, but a little cleaner
a = [:open, 1, :open, 2, 3, :close, 4, :close, :open, 5, :close]
eval(a.to_s.gsub(':open,','[').gsub(', :close',']'))
#=> [[1, [2, 3], 4], [5]]

How to insert a new element in between all elements of a Ruby array?

I have an Array and want to insert a new element in between all elements, someway like the join method. For example, I have
[1, [], "333"]
and what I need is
[1, {}, [], {}, "333"]
Note a new empty hash was inserted in between all elements.
Edit:
Currently what I have is:
irb(main):028:0> a = [1, [], "333"]
=> [1, [], "333"]
irb(main):029:0> a = a.inject([]){|x, y| x << y; x << {}; x}
=> [1, {}, [], {}, "333", {}]
irb(main):030:0> a.pop
=> {}
irb(main):031:0> a
=> [1, {}, [], {}, "333"]
irb(main):032:0>
I want to know the best way.
[1, 2, 3].flat_map { |x| [x, :a] }[0...-1]
#=> [1, :a, 2, :a, 3]
FYI, that function is called intersperse (at least in Haskell).
[Update] If you want to avoid the slice (that created a copy of the array):
[1, 2, 3].flat_map { |x| [x, :a] }.tap(&:pop)
#=> [1, :a, 2, :a, 3]
Another similar solution uses #product :
[1, 2, 3].product([{}]).flatten(1)[0...-1]
# => [ 1, {}, 2, {}, 3 ]
a = [1,2,3]
h, *t = a
r = [h]
t.each do |e|
r.push({}, e)
end
r #=> [1, {}, 2, {}, 3]
You could do something like:
a = [1, [], "333"]
new_a = a.collect {|e| [e, {}]}.flatten(1)
=> [1, {}, [], {}, "333", {}]
You need to do .flatten(1) because it will flatten your blank array without it.
Or as #David Grayson says in the comment, you can do a flat_map which will do the same thing.
a.flat_map {|e| [e, {}]}
=> [1, {}, [], {}, "333", {}]
#tokland has the correct answer if the last {} is not necessary. You return a slice from 0 to length - 1 or [0..-1].
Another one that's similar to Tokland's:
xs.inject([]){|x,y| x << y << {}}[0...-1]
One approach is to zip another array of desired elements and then flatten it with depth = 1:
> arr = [1, [], "333"]
> element = {}
> interspersed = arr.zip([element] * (arr.size - 1)).flatten(1).compact
> # [1, {}, [], {}, "333" ]
You can extend Array to make this behavior more accessible.
class Array
def intersperse(elem)
self.zip([elem] * (self.size - 1)).flatten(1).compact
end
end
e.g.,
[43] pry(main)> [1,2,3].intersperse('a')
=> [1, "a", 2, "a", 3]
[1, 2, 3, 4, 5].inject { |memo, el| Array(memo) << {} << el }
#=> [1, {}, 2, {}, 3, {}, 4, {}, 5]
inject will use the first element to start with, so you don't need to mess with indices.
irb(main):054:0* [1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(1).flat_map {|e| e << "XXX"}[0...-1]
=> [1, "XXX", 2, "XXX", 3, "XXX", 4, "XXX", 5, "XXX", 6, "XXX", 7, "XXX", 8, "XXX", 9]
irb(main):055:0> [1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(2).flat_map {|e| e << "XXX"}[0...-1]
=> [1, 2, "XXX", 3, 4, "XXX", 5, 6, "XXX", 7, 8, "XXX", 9]
irb(main):056:0> [1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(3).flat_map {|e| e << "XXX"}[0...-1]
=> [1, 2, 3, "XXX", 4, 5, 6, "XXX", 7, 8, 9]
irb(main):057:0> [1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(4).flat_map {|e| e << "XXX"}[0...-1]
=> [1, 2, 3, 4, "XXX", 5, 6, 7, 8, "XXX", 9]
irb(main):058:0> [1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(5).flat_map {|e| e << "XXX"}[0...-1]
=> [1, 2, 3, 4, 5, "XXX", 6, 7, 8, 9]
irb(main):059:0> [1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(6).flat_map {|e| e << "XXX"}[0...-1]
=> [1, 2, 3, 4, 5, 6, "XXX", 7, 8, 9]
irb(main):060:0> [1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(7).flat_map {|e| e << "XXX"}[0...-1]
=> [1, 2, 3, 4, 5, 6, 7, "XXX", 8, 9]
irb(main):061:0> [1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(8).flat_map {|e| e << "XXX"}[0...-1]
=> [1, 2, 3, 4, 5, 6, 7, 8, "XXX", 9]
irb(main):062:0> [1, 2, 3, 4, 5, 6, 7, 8, 9].each_slice(9).flat_map {|e| e << "XXX"}[0...-1]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
irb(main):063:0>

Resources