I've an entity and I want to call each element in the entity with a function and pass an argument with it.
I know I can call the function by using entity.each(&:calculate) but I want to pass argument to the function.
def calculate(x)
puts "#{x}"
end
I'm trying with entity.each(&:calculate, x)
Here & converts the method to a proc. As far as I'm aware allowing passing arguments is an open issue: https://bugs.ruby-lang.org/issues/12115
I would simply call the block explicitly
entity.each{ |el| el.calculate(x) }
Related
I have a third party API that has an event listener adding function which takes as parameter a callback function to be triggered when the event occurs. I would like to pass argument to that callback function. I'm looking for Lua's equivalent of JavaScript's bind.
The Lua code:
EventListenerAddingFunction(myCallbackFunction); // I want to add a param to the callback here
How I would do it in JS:
EventListenerAddingFunction(myCallbackFunction.bind({}, myParameter));
Can this be done in Lua?
No Lua doesn't have this feature, so closest I can think of would be making a closure-wrapper:
EventListenerAddingFunction(function(...) myCallbackFunction({}, myParameter, ...) end)
This passes your parameter everytime the callback is called, all other callback parameters will be passed next. If you don't know your parameters use ... (I don't know them so I used varargs), it's better if you pass exact amount of parameters.
I'm trying to decorate multiple functions with a function decorator, and I want to get the parameters of a function that I'm gonna decorate (in this case called fun in the parameters) and I want to pass as an argument to the returned function (in this case called func) the arguments of the gotten function from the parameters (which is called fun)
So it may look like this:
local function decorator(fun)
local function func(fun.args)
-- Write here custom behaviour to add to the function 'fun'
fun(fun.args)
end
return func
end
However, obviously there is no such thing as fun.args that was just a way of explaining with more exactitude to you what I want. Take in mind this, I DON'T know the function I want to decorate, and the functions I want to decorate may be different to each other, so this would be a way of ADDING a custom behaviour to a function (as you can see in the code example above)
So, is there a way to do what I'm needing?
Lua supports varargs via .... In your case, you'd use it like this:
local function decorator(fun)
local function func(...)
-- Write here custom behaviour to add to the function 'fun'
fun(...)
end
return func
end
And if you want to use the arguments in the "custom behaviour" section, then you can do local args = {...}, and then access them numerically (e.g., args[1] would contain the first argument).
I somehow found the call() method is on every function.
Using this method I could change my if (callback != null) callback() to callback?.call().
So I tried to find the implementation and document of call(), but I couldn't. Is it just built-in method? What will be the implementation of this method? Function.apply() will be called inside it?
All Dart functions (objects which has a function type rather than an class/interface type) have a call method.
The call method has the same function type as the function itself, and it behaves exactly the same when you call it. You could even say that calling a function is implicitly calling its call method.
And, not by coincidence, the specification actually does say that: If you write the function invocation e1(e2, e3), then the compiler checks if e1 has call method, and if so converts it to the method invocation e1.call(e2, e3).
Other Dart objects may have a call method too. It's just a normal method for interface types, but if class C has a call method like int call(int x) => ..., and c has type C, then c(e2, e3) is also converted to c.call(e2, e3). It has to be a call method, not just a call getter returning a function.
I'm looking into blocks at the moment, and they have stumped me.
I used this as an example:
class ProcExample
attr_reader :proc_class
def initialize(&block)
#stored_proc = block
#proc_class = #stored_proc.class
end
def use_proc(arg)
#stored_proc.call(arg)
end
end
eg = ProcExample.new {|t| puts t}
p eg.proc_class
p eg.use_proc("Whoooooooo")
Now I kind of (not really( understand how the block is passed into #stored_proc. I used #proc_class because I was curious what class the block object was actually stored as.
But what if I wanted to store a block in a regular variable?
E.g.:
block_object = {|param| puts param**2}
But I found that this is treated as a Hash and not a block/proc. Naturally an error arises. I've tried assigning it with an ampersand in the variable name, and at the beginning of the block but that doesn't work.
Eventually I was wondering if it was possible to call a function and replace the block with a variable containing the block.
Like so:
(1..10).each block_object
Is this possible in Ruby?
You cannot assign blocks to a variable.
Blocks aren't really objects. They are special syntax for passing code to a higher-order method. If you want a piece of executable code that you can assign to a variable, pass around and manipulate, you need to use a Proc object.
There are two kinds of Procs: lambdas and regular procs. They behave differently in two aspects: argument binding semantics and return semantics. lambdas bind arguments like methods and return returns from the lambda, just like return in a method returns from the method. Regular procs bind arguments like blocks and return returns from the enclosing method, not the proc, just like return in a block.
Regular procs can be created by passing a block to Proc.new or alternatively to Kernel#proc. Lambdas can be created by passing a block to Kernel#lambda or with the "stabby lambda" literal syntax:
lambda_object = ->param { puts param**2 }
In order to convert Procs to blocks and the other way around, Ruby has the unary prefix & modifier. This modifier is only valid in parameter lists and argument lists. When used in a parameter list, it means "wrap the block in a proc and bind it to this variable". When used in an argument list. it means "unwrap this proc into a block (and if it's not a proc already, call to_proc on it first) and pass it as a block argument".
(1..10).each(&lambda_object)
I'm surprised that you haven't already seen the unary prefix & modifier used in this way, it is actually fairly common, e.g. in something like ['1', '2'].map(&:to_s).
Another kind of object that also represents a piece of executable code is a Method object. It supports some of the same interface as Procs do, in particular #call, #to_proc, #arguments, #arity etc. There are two ways to get a Method object: either grab a method that is bound to a receiver from that receiver using the Object#method method or grab an UnboundMethod object from a class or module (e.g. using Module#instance_method) and bind it to a receiver using UnboundMethod#bind which will return a Method object.
Since Method implements to_proc, you can pass it to a method as a block using the unary prefix & modifier, e.g.:
# Warning: extremely silly example :-)
ary = []
(1..10).each(&ary.method(:<<))
ary
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
ary = []
(1..10).each(&Array.instance_method(:<<).bind(ary))
ary
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
You are looking for a proc object, I believe.
block = proc { ... }
You can use a proc or lambda. There are some subtle differences between them; and between Ruby versions. A good overview can been seen here: https://www.youtube.com/watch?v=VBC-G6hahWA given by Peter Cooper
Since Squeak is purely Object Oriented I'm fairly certain that you should be able to pass functions as parameters to other functions, but when I was researching on this I couldn't find any information about this. Is my intuition correct? And if so, how is it done and how do I invoke them afterwards?
Longer answer.
To pass a piece of executable code to a method, use a block.
The method definition is
method: aBlock
aBlock value
and you execute it as follows
object method: [ Transcript show: 'hello' ].
if you want to pass a parameter to the piece of code, use a block with an argument.
The method definition is
method: aBlock
aBlock value: 'parameter'
and you execute it as follows
object method: [ :arg | Transcript show: arg ].
the same can be done with 2 or unlimited parameters, using the methods value:value: and valueWithArguments: of the block.
If you pass in a symbol, you can also use value: to execute it. A symbol is actually equivalent to a block of the form [ :arg | arg symbol ].
You're confusing two different things. The only real "functions" you pass around in Smalltalk are blocks, which you pass just by writing a block as an argument (like you do with every ifTrue:). If you want to send a message to an object but have the message be determined dynamically, you can pass the message name as a symbol (e.g. #value) and send it to some object (e.g. with perform:). You don't pass instance methods themselves. Either pass a selector symbol or pass a block that sends a message to call the method.