Confusion with yield call to outer block - ruby

CODE-I
def sample
x = "hi"
puts " #{x}"
x = yield
puts " #{x}"
end
In the below code block {} from here => sample {"hellooo"} called
yield and assigned "hellooo" to x. Looks good and as expected.
sample{'helloo'}
# >> hi
# >> helloo
CODE-II
o = Object.new
def o.each
x = yield
p x
x = yield
p x
x = yield
p x
end
e = o.to_enum # => #<Enumerator: #<Object:0x007fd1d20494e8>:each>
Why the same not happened in the below call with e.next "sample", as the p didn't printed anything?
e.next {"sample"} # => nil
e.next # => nil
# >> nil
EDIT (Here how enum#feed did the change with the help of yield?)
o = Object.new
=> #<Object:0x2299d88>
def o.each
x = yield
p x
x = yield
p x
x = yield
p x
end
=> nil
e=o.to_enum
=> #<Enumerator: #<Object:0x2299d88>:each>
e.next
=> nil
e.feed "hi"
=> nil
e.next
"hi"
=> nil

next does not take a block. So if you pass it one, it simply ignores it.
It is not possible to simulate something being returned from the block when using the next method of an enumerator. When using an to_enum, the block given to the each method will always return nil except if a value has previously supplied by the feed method.

Related

Is there a Ruby method for determining if all instance variables of two instances of the same class are equal?

Is there a Ruby method for comparing two objects based on whether all of their instance variables are equal? The method would behave like this code.
class Coordinates
attr_reader :x, :y
def initialize(x, y)
#x = x
#y = y
end
end
coordinates1 = Coordinates.new(0, 0)
coordinates2 = Coordinates.new(0, 0)
coordinates3 = Coordinates.new(1, 0)
compare(coordinates1, coordinates1) # => true
compare(coordinates1, coordinates2) # => true
compare(coordinates1, coordinates3) # => false
Does this method or something similar exist?
There is no built-in method for this, but you could quite easily write one. However, I think you're asking an XY question.
Here is what I think the question is supposed to say:
How should I define a method to check that two Coordinates instances are equal?
And here's my answer:
Define a custom == method:
class Coordinates
attr_reader :x, :y
def initialize(x, y)
#x = x
#y = y
end
def ==(other)
return super unless other.is_a?(Coordinates)
x == other.x && y == other.y
end
end
...But in the spirit of StackOverflow, here's some meta-programming to check whether all instance variables have the same name and value:
# returns true if all objects have the same instance variable names and values
def compare(*objects)
objects.map do |object|
object.instance_variables.map do |var_name|
[var_name, object.instance_variable_get(var_name)]
end
end.uniq.count == 1
end
Case 1
class A
def initialize(x,y)
#x = x
#y = y
end
def m
#x = 5
#y = 6
end
end
a1 = A.new(1,2)
#=> #<A:0x00005d22a3878048 #x=1, #y=2>
a1.m
a1 #=> #<A:0x00005d22a3878048 #x=5, #y=6>
a2 = A.new(3,4)
#=> #<A:0x00005d22a38b5330 #x=3, #y=4>
a2.m
a2 #=> #<A:0x00005d22a38b5330 #x=5, #y=6>
Then,
a1.instance_variables.all? { |e|
a1.instance_variable_get(e) == a2.instance_variable_get(e) }
#=> true
tells us that the values of #x and the values of #y are the same for both instances.
Case 2
Now let's change the code so that another instance variable is added conditionally.
class A
def initialize(x,y)
#x = x
#y = y
end
def m
#z = 3 if #x == 3
#x = 5
#y = 6
end
end
a1 = A.new(1,2)
#=> #<A:0x000057d1fd563c78 #x=1, #y=2>
a1.m
a1 #=> #<A:0x000057d1fd27f200 #x=5, #y=6>
a2 = A.new(3,4)
#=> #<A:0x000057d1fd57cb38 #x=3, #y=4>
a2.m
a2 #=> #<A:0x000057d1fd2f9e10 #x=5, #y=6, #z=3>
At this point are all instance variables of one of these instances equal to the corresponding instance variable of the other instance? No, because a2 has an additional instance variable, #z. Therefore,
a1.instance_variables.all? { |e|
a1.instance_variable_get(e) == a2.instance_variable_get(e) }
#=> true
gives the wrong answer, for obvious reasons. Perhaps we could test as follows:
a1.instance_variables.all? { |e|
a1.instance_variable_get(e) == a2.instance_variable_get(e) } &&
a2.instance_variables.all? { |e|
a1.instance_variable_get(e) == a2.instance_variable_get(e) }
#=> true && false => false
This has a gotcha, however, if #z equals nil.
Case 3
class A
def initialize(x,y)
#x = x
#y = y
end
def m
#z = nil if #x == 3
#x = 5
#y = 6
end
end
a1 = A.new(1,2)
#=> #<A:0x000057d1fd2d18e8 #x=1, #y=2>
a1.m
a1 #=> #<A:0x000057d1fd2d18e8 #x=5, #y=6>
a2 = A.new(3,4)
#=> #<A:0x000057d1fd46b460 #x=3, #y=4>
a2.m
a2
#=> #<A:0x000057d1fd46b460 #x=5, #y=6, #z=nil>
a1.instance_variables.all? { |e|
a1.instance_variable_get(e) == a2.instance_variable_get(e) } &&
a2.instance_variables.all? { |e|
a1.instance_variable_get(e) == a2.instance_variable_get(e) }
#=> true && true => true
We obtain this incorrect result because:
class A
end
A.new.instance_variable_get(:#z)
#=> nil
We therefore must confirm that if one instance has an instance variable named e, so does the other instance, and that each pair of instance variables with the same name are equal. One way to do that is as follows:
(a1.instance_variables.sort == a2.instance_variables.sort) &&
a1.instance_variables.all? { |e|
a1.instance_variable_get(e) == a2.instance_variable_get(e) }
#=> false && true => false
See Enumerable#all?, Object#instance_variables and Object#instance_variable_get.

How to change a value in an array via a hash?

I want to change the value of an array via a hash, for example:
arr = ['g','g','e','z']
positions = {1 => arr[0], 2 => arr[1]}
positions[1] = "ee"
Problem is that the one that changed is hash and not array. When I do p arr It still outputs ['g','g','e','z']. Is there a way around this?
You're going to need to add another line of code to do what you want:
arr = ['g','g','e','z']
positions = {1 => arr[0], 2 => arr[1]}
positions[1] = "ee"
arr[0] = positions[1]
Another option would be to make a method that automatically updated the array for you, something like this:
def update_hash_and_array(hash, array, val, index)
# Assume that index is not zero indexed like you have
hash[index] = val
array[index - 1] = val
end
update_hash_and_array(positions, arr, "ee", 1) # Does what you want
This is possible to code into your hash using procs.
arr = ['g','g','e','z']
positions = {1 => -> (val) { arr[0] = val } }
positions[1].('hello')
# arr => ['hello', 'g', 'e', 'z']
You can generalize this a bit if you want to generate a hash that can modify any array.
def remap_arr(arr, idx)
(idx...arr.length+idx).zip(arr.map.with_index{|_,i| -> (val) {arr[i] = val}}).to_h
end
arr = [1,2,3,4,5,6]
positions = remap_arr(arr, 1)
positions[2].('hello')
# arr => [1,'hello',3,4,5,6]
positions[6].('goodbye')
# arr => [1,'hello',3,4,5,'goodbye']
But I'm hoping this is just a thought experiment, there is no reason to change the way array indexing behavior works to start from 1 rather than 0. In such cases, you would normally just want to offset the index you have to match the proper array indexing (starting at zero). If that is not sufficient, it's a sign you need a different data structure.
#!/usr/bin/env ruby
a = %w(q w e)
h = {
1 => a[0]
}
puts a[0].object_id # 70114787518660
puts h[1].object_id # 70114787518660
puts a[0] === h[1] # true
# It is a NEW object of a string. Look at their object_ids.
# That why you can not change value in an array via a hash.
h[1] = 'Z'
puts a[0].object_id # 70114787518660
puts h[1].object_id # 70114574058580
puts a[0] === h[1] # false
h[2] = a
puts a.object_id # 70308472111520
puts h[2].object_id # 70308472111520
puts h[2] === a # true
puts a[0] === h[2][0] # true
# Here we can change value in the array via the hash.
# Why?
# Because 'h[2]' and 'a' are associated with the same object '%w(q w e)'.
# We will change the VALUE without creating a new object.
h[2][0] = 'X'
puts a[0] # X
puts h[2][0] # X
puts a[0] === h[2][0] # true

Turning a method into an enumerable method

I rewrote the map method:
def my_map(input, &block)
mod_input = []
x = -1
while x < input.length - 1
x = x + 1
if block == nil
return input
break
end
mod_input.push(block.call(input[x]))
end
return mod_input
end
I need to call this code as I would call map or reverse. Does anyone know the syntax for that?
Are you asking how you put a method into a module? That's trivial:
module Enumerable
def my_map(&block)
mod_input = []
x = -1
while x < length - 1
x = x + 1
if block == nil
return self
break
end
mod_input.push(block.call(self[x]))
end
return mod_input
end
end
[1, 2, 3, 4, 5].my_map(&2.method(:*))
# => [2, 4, 6, 8, 10]
Or are you asking how to make your method an Enumerable method? That's more involved: your method currently uses many methods that are not part of the Enumerable API. So, even if you make it a member of the Enumerable module, it won't be an Enumerable method. Enumerable methods can only use each or other Enumerable methods. You use length and [] both of which are not part of the Enumerable interface, for example, Set doesn't respond to [].
This would be a possible implementation, using the Enumerable#inject method:
module Enumerable
def my_map
return enum_for(__method__) unless block_given?
inject([]) {|res, el| res << yield(el) }
end
end
[1, 2, 3, 4, 5].my_map(&2.method(:*))
# => [2, 4, 6, 8, 10]
A less elegant implementation using each
module Enumerable
def my_map
return enum_for(__method__) unless block_given?
[].tap {|res| each {|el| res << yield(el) }}
end
end
[1, 2, 3, 4, 5].my_map(&2.method(:*))
# => [2, 4, 6, 8, 10]
Note that apart from being simply wrong, your code is very un-idiomatic. There is also dead code in there.
the break is dead code: the method returns in the line just before it, therefore the break will never be executed. You can just get rid of it.
def my_map(&block)
mod_input = []
x = -1
while x < length - 1
x = x + 1
if block == nil
return self
end
mod_input.push(block.call(self[x]))
end
return mod_input
end
Now that we have gotten rid of the break, we can convert the conditional into a guard-style statement modifier conditional.
def my_map(&block)
mod_input = []
x = -1
while x < length - 1
x = x + 1
return self if block == nil
mod_input.push(block.call(self[x]))
end
return mod_input
end
It also doesn't make sense that it is in the middle of the loop. It should be at the beginning of the method.
def my_map(&block)
return self if block == nil
mod_input = []
x = -1
while x < length - 1
x = x + 1
mod_input.push(block.call(self[x]))
end
return mod_input
end
Instead of comparing an object against nil, you should just ask it whether it is nil?: block.nil?
def my_map(&block)
return self if block.nil?
mod_input = []
x = -1
while x < length - 1
x = x + 1
mod_input.push(block.call(self[x]))
end
return mod_input
end
Ruby is an expression-oriented language, the value of the last expression that is evaluated in a method body is the return value of that method body, there is no need for an explicit return.
def my_map(&block)
return self if block.nil?
mod_input = []
x = -1
while x < length - 1
x = x + 1
mod_input.push(block.call(self[x]))
end
mod_input
end
x = x + 1 is more idiomatically written x += 1.
def my_map(&block)
return self if block.nil?
mod_input = []
x = -1
while x < length - 1
x += 1
mod_input.push(block.call(self[x]))
end
mod_input
end
Instead of Array#push with a single argument it is more idiomatic to use Array#<<.
def my_map(&block)
return self if block.nil?
mod_input = []
x = -1
while x < length - 1
x += 1
mod_input << block.call(self[x])
end
mod_input
end
Instead of Proc#call, you can use the .() syntactic sugar.
def my_map(&block)
return self if block.nil?
mod_input = []
x = -1
while x < length - 1
x += 1
mod_input << block.(self[x])
end
mod_input
end
If you don't want to store, pass on or otherwise manipulate the block as an object, there is no need to capture it as a Proc. Just use block_given? and yield instead.
def my_map
return self unless block_given?
mod_input = []
x = -1
while x < length - 1
x += 1
mod_input << yield(self[x])
end
mod_input
end
This one is opinionated. You could move incrementing the counter into the condition.
def my_map
return self unless block_given?
mod_input = []
x = -1
while (x += 1) < length
mod_input << yield(self[x])
end
mod_input
end
And then use the statement modifier form.
def my_map
return self unless block_given?
mod_input = []
x = -1
mod_input << yield(self[x]) while (x += 1) < length
mod_input
end
Also, your variable names could use some improvements. For example, what does mod_input even mean? All I can see is that it is what you output, so why does it even have "input" in its name? And what is x?
def my_map
return self unless block_given?
result = []
index = -1
result << yield(self[index]) while (index += 1) < length
result
end
This whole sequence of initializing a variable, then mutating the object assigned to that variable and lastly returning the object can be simplified by using the K Combinator, which is available in Ruby as Object#tap.
def my_map
return self unless block_given?
[].tap {|result|
index = -1
result << yield(self[index]) while (index += 1) < length
}
end
The entire while loop is useless. It's just re-implementing Array#each, which is a) unnecessary because Array#each already exists, and b) means that your my_map method will only work with Arrays but not other Enumerables (for example Set or Enumerator). So, let's just use each instead.
def my_map
return self unless block_given?
[].tap {|result|
each {|element|
result << yield(element)
}
}
end
Now it starts to look like Ruby code! What you had before was more like BASIC written in Ruby syntax.
This pattern of first creating a result object, then modifying that result object based on each element of a collection and in the end returning the result is very common, and it even has a fancy mathematical name: Catamorphism, although in the programming world, we usually call it fold or reduce. In Ruby, it is called Enumerable#inject.
def my_map
return self unless block_given?
inject([]) {|result, element|
result << yield(element)
}
end
That return self is strange. map is supposed to return a new object! You don't return a new object, you return the same object. Let's fix that.
def my_map
return dup unless block_given?
inject([]) {|result, element|
result << yield(element)
}
end
And actually, map is also supposed to return an Array, but you return whatever it is that you called map on.
def my_map
return to_a unless block_given?
inject([]) {|result, element|
result << yield(element)
}
end
But really, if you look at the documentation of Enumerable#map, you will find that it returns an Enumerator and not an Array when called without a block.
def my_map
return enum_for(:my_map) unless block_given?
inject([]) {|result, element|
result << yield(element)
}
end
And lastly, we can get rid of the hardcoded method name using the Kernel#__method__ method.
def my_map
return enum_for(__method__) unless block_given?
inject([]) {|result, element|
result << yield(element)
}
end
Now, that looks a lot better!
class Array
def my_map(&block)
# your code, replacing `input` with `self`
end
end
The code itself is not really idiomatic Ruby - while is very rarely used for iteration over collections, and if you don't need to pass a block somewhere else, it is generally cleaner to use block_given? instead of block.nil? (let alone block == nil), and yield input[x] instead of block.call(input[x]).

Is there a Ruby shorthand for assigning a value from an array only if it is not nil?

I have the following code:
via = reminders_array[i]['value']['bot-input-keyword'] unless reminders_array[i]['value']['via'].nil?
and
collection = json_element['COLLECTION']['$'] unless json_element['COLLECTION'].nil?
When I search for examples, I saw people use ||= but I can't quite understand its use, especially in the second case.
Consider the the following statements:
e #=> NameError: undefined local variable or method `e'...
if false
e = 7
end
e #=> nil
f #=> NameError: undefined local variable or method `f'
f = 7 if false
f #=> nil
As you see, Ruby raises an exception if the value of a local variable (e or f) is sought, but if the variable first appears in a statement, but is not assigned a value, Ruby sets its value to nil. We see that:
a = b unless c.nil?
is the same as:
a = b if c
which is the same as:
a = (c ? b : nil)
which is the same as:
a = c && b
To see why the last expression is equivalent to the preceding two, let's try a couple of examples, both with:
b = 4
c = 2
c && b #=> (2 && 4) => 4
c = nil
c && b #=> (nil && 4) => nil
So I believe you want:
via = reminders_array[i]['value']['via'] &&
reminders_array[i]['value']['bot-input-keyword']
You asked about ||=, which is a form of abbreviated assignment. When Ruby's sees a ||= b she makes the assignment a = b if a is nil or false:
a || a = b
Two more examples, with b still equal to 4:
a = 2
a ||= 4 #=> a || a = 4 => a => 2 || a = 4) => 2
a = nil
a ||= 4 #=> a || a = 4 => a => nil || a = 4 #=> 4
So if a is nil, a remains nil; else a is set to b.
A common use of ||= is:
a = nil
(a ||= []) << 4
#=> [4]
a = [4]
(a ||= []) << 6
#=> [4,6]
In the first instance, a is nil, so a ||= [] converts a to an empty array, to which it appends 4. In the second case, a ([4]) is not nil, so a ||= [] leaves a unchanged ([4]). 6 is then appended to a, making a [4,6].
In addition to ||= there are:
a &&= b #=> a && a = b
a += b #=> a = a + b
a *= b #=> a = a * b
and others (see the doc). A word about a && b. If a is nil, a && b is nil. If a is not nil, a && b is b. Notice that for operators op other than || and &&, a op= b is expanded to a = a op b.

Filter arrays with bitmask or other array in Ruby

I was wondering if there was an Array method in Ruby that allows to filter an array based on another array or a bitmask.
Here is an example and a quick implementation for illustration purposes:
class Array
def filter(f)
res = []
if f.is_a? Integer
(0...self.size).each do |i|
res << self[i] unless f[i].nil? || 2**i & f == 0
end
else
(0...self.size).each do |i|
res << self[i] unless f[i].nil? || f[i] == 0
end
end
return res
end
end
Example:
%w(a b c).filter([1, 0, 1]) ==> ['a', 'c']
%w(a b c).filter(4) ==> ['c']
%w(a b c).filter([1]) ==> ['a']
Thanks!
In ruby 1.9 Fixnum#[] gives you bit values at a particular position, so it will work for both integers and arrays. I'm thinking something like this:
class Array
def filter f
select.with_index { |e,i| f[i] == 1 }
end
end
%w(a b c).filter([1, 0, 1]) #=> ['a', 'c']
%w(a b c).filter(4) #=> ['c']
%w(a b c).filter(5) #=> ['a', c']
%w(a b c).filter([1]) #=> ['a']
class Array
def filter(f)
f = f.to_s(2).split("").map(&:to_i) unless Array === f
reverse.reject.with_index{|_, i| f[-i].to_i.zero?}
end
end

Resources