How to `break` a outside loop in closure (Proc, lambda)? - ruby

loop { break } can work fine, but
block = Proc.new { break }
# or
# block = lambda { break }
loop(&block) # => LocalJumpError: break from proc-closure
Is it possible to break in a block variable ?
Update:
A example to explain more:
def odd_loop
i = 1
loop do
yield i
i += 2
end
end
def even_loop
i = 2
loop do
yield i
i += 2
end
end
# This work
odd_loop do |i|
puts i
break if i > 10
end
# This doesn't work
break_greater_10 = Proc.new do |i|
puts i
break if i > 10
end
odd_loop(&break_greater_10) # break from proc-closure (LocalJumpError)
even_loop(&break_greater_10) # break from proc-closure (LocalJumpError)
As my comprehension, Proc.new should work same as block (it can return a function from block), but I don't understand why can't break a loop.
P.S. Sorry for my bad english >~<

To solve this problem you could
raise StopIteration
this worked for me.

To return from a block you can use the next keyword.
def foo
f = Proc.new {next ; p 1}
f.call
return 'hello'
end
puts foo # => 'hello' , without 1

Related

Next-ing from child each loop in Ruby

I have this bit of code:
gates.each do |key, value, temp|
unless value.class == Output
temp = value.in1
gates.each do |k, v|
if v.out == temp
value.base_distance += 1
#do a thing
end
end
end
end
What I want to happen is when the #do a thing comment inside the conditional is reached it should break out of the inner .each loop and move on to the next instance of the outer .each loop, essentially executing a next. How would I do that from inside the conditional?
TL;DR use break.
Here is the MCVE:
[1,2].each do |o|
puts "Outer: #{o}"
[1,2,3].each do |i|
break if i.even?
puts "Inner: #{i}"
end
end
#⇒ Outer: 1
# Inner: 1
# Outer: 2
# Inner: 1
FWIW, one might pass an argument to break to be returned from the block. This might be needed to emulate the next after break:
[1,2].each do |o|
puts "Outer: #{o}"
inner =
[1,2,3].each do |i|
break :next if i.even?
puts "Inner: #{i}"
end
next if inner == :next
...
end

Get local variables of previous scope

I am making a Ruby REPL to be used inside an application. I made code:
a = 1
b = 2
currentScope = []
Kernel.local_variables.each do |var|
currentScope << [var,Kernel.eval(var.to_s)]
end
launchREPL(currentScope)
Inside the REPL, I can execute the following code:
#a #=>1
#a+#b #=>3
Ideally I wouldn't have to write the four lines of code before I launch the REPL, and instead I would like to run them inside the launchREPL function. However this would require access to the previous scope from inside the launchREPL function.
Test1
Most notably I tried:
launchREPL(Kernel)
When I do the following:
def launchREPL(scope)
F = 0
puts scope.local_variables # => [:F]
end
it is apparent that this method is not valid.
Test2
launchREPL(Kernel.binding)
def launchREPL(scope)
Kernel.binding.local_variables #= Error: private method 'local_variables' called for #<Binding>
end
Is there any way to do what I'm trying to do?
Edit: P.S. This is currently the code inside launchREPL:
def launchREPL(scope=nil,winName="Ruby REPL")
# ICM RB file Begin:
puts "\"Starting REPL...\""
__b = binding #Evaluating in a binding, keeps track of local variables
__s = ""
###############################################################################
# SEND INSTANCE VARIABLES TO REPL
###############################################################################
#
#How to prepare scope
# currentScope = []
# Kernel.local_variables.each do |var|
# currentScope << [var,Kernel.eval(var.to_s)]
# end
# launchREPL(currentScope)
if scope != nil
scope.each do |varDef|
__b.instance_variable_set "##{varDef[0].to_s}" , varDef[1]
__b.eval("##{varDef[0].to_s} = __b.instance_variable_get(:##{varDef[0].to_s})")
end
end
# to get instance variables: __b.instance_variable_get(__b.instance_variables[0])
# or better: __b.instance_variable_get(:#pipe1)
#
###############################################################################
bStartup = true
while bStartup || __s != ""
# If startup required skip evaluation step
if !bStartup
#Evaluate command
begin
__ret = __s + "\n>" + __b.eval(__s).to_s
rescue
__ret = __s + "\n> Error: " + $!.to_s
end
puts __ret
else
#REPL is already running
bStartup = false
end
#Read user input & print previous output
__s = WSApplication.input_box(__ret,winName,"")
__s == nil ? __s = "" : nil
end
end
Although what you are trying to achieve is unclear and there are definitely many ways to do it properly, every ruby method might be called with Object#send approach:
def launchREPL(scope)
scope.send :local_variables #⇒ here you go
end
a = 42
launchREPL(binding).include?(:a)
#⇒ true
Sidenote: this is how your “4 lines” are usually written in ruby:
local_variables.map { |var| [var, eval(var.to_s)] }
And this is how they should be written (note Binding#local_variable_get):
local_variables.map { |var| [var, binding.local_variable_get(var)] }
The summing up:
def launchREPL(scope)
vars = scope.send(:local_variables).map do |var|
[var, scope.local_variable_get(var)]
end
# some other code
end
a = 42
launchREPL(binding).to_h[:a]
#⇒ 42
This won’t fit the comment, so I would post it as an answer.
def launchREPL(scope = nil, winName = "Ruby REPL")
puts '"Starting REPL..."'
scope.eval('local_variables').each do |var|
instance_variable_set "##{var}", scope.eval(var.to_s)
end if scope
s = ""
loop do
ret = begin
"#{s}\n> #{eval(s)}"
rescue => e
"#{s}\n> Error: #{e.message}"
end
puts ret
# s = WSApplication.input_box(ret, winName, "")
# break if s.empty?
s = "100 * #a" # remove this line and uncomment 2 above
end
end
a = 42
launchREPL(binding)
This is how your function should be written (I have just make it looking as ruby code.) The above works (currently it has no break at all, but you can see as it’s calculating 4200 infinitely.)

No puts or gets inside instance method - Ruby

This is really driving me up a wall.
I have an instance method I'm trying to debug, but I'm running into an issue where my puts and gets aren't showing up inside the instance method.
Code:
#! /usr/bin/env ruby
class Calculator
def evaluate(string)
ops = string.split(' ')
ops.map! do |item|
if item.is_a? Numeric
return item.to_i
else
return item.to_sym
end
end
puts "Got #{string}" #Doesn't output
puts "Converted to #{ops}" #This too
opscopy = ops.clone
ops.each.with_index do |item, index|
if item == :* || item == :/
opscopy[index] = ops[index-1].send(item, ops[index+1])
opscopy[index-1] = opscopy[index+1] = nil
end
end
ops = opscopy.compact
puts "After multi/div #{ops}"
ops.each.with_index do |item, index|
if item == :+ || item == :-
opscopy[index] = ops[index-1].send(item, ops[index+1])
opscopy[index-1] = opscopy[index+1] = nil
end
end
puts "After +/- #{opscopy.compact}"
opscopy.compact.first
end
end
item = Calculator.new.evaluate "4 * 2"
puts "#{item} == 8" #Prints :(
Output:
action#X:~/workspace/ruby$ ./calculator.rb
4 == 8
That return in your map! block is where the problem is.
ops.map! do |item|
if item.is_a? Numeric
return item.to_i # returns from method
else
return item.to_sym # returns from method
end
end
You are returning the method in your map! block before the puts is called.
Change the map! block to:
ops.map! do |item|
item.send(item.is_a?(Numeric) ? :to_i : :to_sym)
end

How to count how many times an iterator will call yield?

I have a method, foo, that yields objects. I want to count the number of objects it yields.
I have
def total_foo
count = 0
foo { |f| count += 1}
count
end
but there's probably a better way. Any ideas for this new Rubyist?
Here's the definition for foo (it's a helper method in Rails):
def foo(resource=#resource)
resource.thingies.each do |thingy|
bar(thingy) { |b| yield b } # bar also yields objects
end
end
Any method that calls yield can be used to build an Enumerator object, on which you can call count, by means of the Object#to_enum method. Remember that when you call count the iterator is actually executed so it should be free of side effects! Following a runnable example that mimics your scenario:
#resources = [[1,2], [3,4]]
def foo(resources = #resources)
resources.each do |thingy|
thingy.each { |b| yield b }
end
end
foo { |i| puts i }
# Output:
# 1
# 2
# 3
# 4
to_enum(:foo).count
# => 4
You can pass an argument to foo:
to_enum(:foo, [[5,6]]).count
# => 2
Alternatively you can define foo to return an Enumerator when it's called without a block, this is the way stdlib's iterators work:
def foo(resources = #resources)
return to_enum(__method__, resources) unless block_given?
resources.each do |thingy|
thingy.each { |b| yield b }
end
end
foo.count
# => 4
foo([[1,2]]).count
# => 2
foo([[1,2]]) { |i| puts i }
# Output:
# 1
# 2
You can pass a block to to_enum that is called when you call size on the Enumerator to return a value:
def foo(resources = #resources)
unless block_given?
return to_enum(__method__, resources) do
resources.map(&:size).reduce(:+) # thanks to #Ajedi32
end
end
resources.each do |thingy|
thingy.each { |b| yield b }
end
end
foo.size
# => 4
foo([]).size
# => 0
In this case using size is sligthly faster than count, your mileage may vary.
Assuming you otherwise only care about the side-effect of foo, you could have foo itself count the iterations:
def foo(resource=#resource)
count = 0
resource.thingies.each do |thingy|
bar(thingy) do |b|
count += 1
yield b
end # bar also yields objects
end
count
end
And then:
count = foo { |f| whatever... }
You can also ignore the return value if you choose, so just:
foo { |f| whatever... }
In cases you don't care what the count is.
There may be better ways to handle all of this depending upon the bigger context.

Ruby: No Block Given error

I keep getting a 'no block given' error when trying to pass the string to the is_tut? method. I am new to Ruby and have no idea what I'm doing wrong. Any and all help would be appreciated.
class Tut
##consonants = ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"]
def is_tut? string
if string =~ /^(([b-df-hj-np-z]ut)|([aeiou\s])|[[:punct:]])+$/i
yield
else
false
end
end
def self.to_tut string
string.each_char do |c|
c += "ut" if ##consonants.find { |i| i == c.downcase }
yield c
end
end
def self.to_english string
array = string.split //
array.each do |c|
if ##consonants.find { |i| i == c.downcase }
array.shift
array.shift
end
yield c
end
end
end
#Tut.to_tut( "Wow! Look at this get converted to Tut!" ) { |c| print c }
# should output : Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!
puts
puts
tut = Tut.to_tut( "Wow! Look at this get converted to Tut!" )
puts "from return: #{tut}"
puts
#Tut.to_tut( "Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!" ) { |c| print c }
# should outout : Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!
puts
puts
#tut = Tut.to_tut( "Wutowut! Lutookut atut tuthutisut gutetut cutonutvuteruttutedut tuto Tututut!" )
#puts "from return: #{tut}"
puts
#tut_string = ""
#Tut.to_tut( "I'm in tut but I want to be in english." ) { |c| tut_string += c }
#puts tut_string
# should output : I'mut inut tututut bututut I wutanuttut tuto bute inut enutgutlutisuthut.
puts
#Tut.to_english( tut_string ) { |c| print c }
# should output : I'm in tut but I want to be in english.
If you have yield within your method definition, that means you have to obligatorily pass a block when you use it (unless the part including it is not executed according to conditioning etc.). (You might already know, but in case you don't: a block is something that is described as {...} or do ... end) And yield will refer to the block.
If you want to make a block optional, then one way to do it is to put the & symbol before the variable name.
def method(argument, &block_argument)
if block_argument # block is given
block_argument.call(argument_for_block) # use call to execute the block
else # the value of block_argument becomes nil if you didn't give a block
# block was not given
end
end
This will allow optional block. Or, as suggested by Squeegy,
def method(argument)
if block_given? # block is given
yield(argument_for_block) # no need to use call to execute the block
else
# block was not given
end
end
will also work.
Because you're calling yield in your to_tut() method, this line will fail:
tut = Tut.to_tut( "Wow! Look at this get converted to Tut!" )
You either need to give a block (as you did in the first commented-out call to Tut.to_tut()), or you need to modify your to_tut() function to make the code block optional:
def self.to_tut string
string.each_char do |c|
c += "ut" if ##consonants.find { |i| i == c.downcase }
yield c if block_given?
end
end
yield requires a block to be passed to to_tut.
When you do:
Tut.to_tut( "Wow! Look at this get converted to Tut!" ) { |c| print c }
It works because it has the block { |c| print c }.
Without a block it will raise the error.

Resources