Is it possible to get the inferred return type of a method call to be used in a macro? - return-type

If the return type of a method is not stated, is it still possible to get the inferred return type to be used in a macro?
class Record
def explicit : String
"name"
end
def inferred
["a", "b"]
end
end
# The following works:
puts {{Record.methods.find { |m| m.name.id == "explicit".id }.return_type }}
# The following does not (because .return_type
# is useful when the method explicitly states the return type):
puts {{Record.methods.find { |m| m.name.id == "inferred".id }.return_type }}

No, macros run before any type inference is done and it's impossible to access inferred types from macros. This is because macros have to be fully expanded before the type checker can correctly infer return types.

Related

Sorbet variable array length

I'm just starting to play around with the sorbet gem. I have a method that expects and returns an array of objects. The thing is, the length of the array is varied. How can I type check the method? I keep getting Expected type [Object], got array of size 2
Here's my method
sig { params(foo: Array[Object]).returns(Array[Object]) }
def bar(foo)
# code to modify some of the attributes
end
tl;dr You have a syntax error. Use T::Array[Object] (not Array[Object]).
You're using incorrect type syntax for arrays:
# typed: strict
extend T::Sig
sig { params(foo: Array[Object]).returns(Array[Object]) }
def bar(foo)
# code to modify some of the attributes
end
→ View on sorbet.run
The errors show:
editor.rb:5: Use T::Array[...], not Array[...] to declare a typed Array https://srb.help/5026
5 |sig { params(foo: Array[Object]).returns(Array[Object]) }
^^^^^^^^^^^^^
Note:
Array[...] will raise at runtime because this generic was defined in the standard library
Autocorrect: Use `-a` to autocorrect
editor.rb:5: Replace with T::Array
5 |sig { params(foo: Array[Object]).returns(Array[Object]) }
^^^^^
editor.rb:5: Use T::Array[...], not Array[...] to declare a typed Array https://srb.help/5026
5 |sig { params(foo: Array[Object]).returns(Array[Object]) }
^^^^^^^^^^^^^
Note:
Array[...] will raise at runtime because this generic was defined in the standard library
Autocorrect: Use `-a` to autocorrect
editor.rb:5: Replace with T::Array
5 |sig { params(foo: Array[Object]).returns(Array[Object]) }
^^^^^
Errors: 2
Why is it like this?
The [] method on Array has special meaning, but Sorbet uses [] for generic type arguments. To get around that, Sorbet uses the T:: namespace for certain generic classes in the standard library:
→ https://sorbet.org/docs/stdlib-generics
What's happening in your case is that this code:
Array[Object]
is equivalent to having written this:
[Object]
(i.e., "make an array of length one containing the value Object"). [Object] in Sorbet happens to be the way to express a 1-tuple.

How to make a Ruby method to pass output parameters (change the value of referenced arguments)?

I'm trying to make a method with output arguments in ruby.
I read differents posts here and here about the discussion of wether ruby pass its arguments by-value or by-reference and
I undersand that on a strict sens, Ruby always pass-by-value, but the value passed is actually a reference. Reason why there is so much debate on this.
I find out that there are several ways to change the value of the referenced variable.
For instance with the replace method when its an Array, a Hash or a String, or merge! when it's a hash.
I found out that with integer, I can change and pass the value outside my method without any special method use.
My question is about other objects.
For instance I want to retrieve the 'id' attribute of an object, and the object reference itself :
class RestaurantController < ApplicationController
def pizza_to_deliver(pizza_name, id_of_the_order, pizza)
# pizza to eat
pizza = Pizza.where(:name => pizza_name).first
# unknown pizza
return false if pizza.nil?
# first customer order about this pizza
id_of_the_order = Orders.where(:pizza_id => pizza.id).first
true
end
end
my_pizza_name = 'margerita'
My_order_id = nil
my_pizza = nil
my_restaurant = RestaurantController.new
if my_restauant.pizza_to_deliver(my_pizza_name, My_order_id, my_pizza) then
puts "Pizza to deliver : #{my_order_id}"
rex_dog.eat(my_pizza)
end
How to make this works ? (order_id and my_pizza remains with nil)
Ruby has only pass by value, just like Python and Java. Also like Python and Java, objects are not values directly, and are manipulated through references.
It seems you already understand how it works -- assigning to a local variable never has any effect on a caller scope. And to "share" information with the caller scope other than returning, you must use some method on the object to "mutate" the object (if such a method exists; i.e. if the object is mutable) that is pointed to by the passed reference. However, this simply modifies the same object rather than giving a reference to a new object, which you want.
If you are not willing to return the value, you can pass a mutable container (like an array of one element) that the called function can then mutate and put whatever in there and have it be seen in the caller scope.
Another option is to have the function take a block. The function would give the block the new value of pizza, and the block (which is given by the caller) can then decide what to do with it. The caller can pass a block that simply sets the pizza in its own scope.
For the most part, out parameters are a workaround for languages that don't have multiple-value return. In Ruby, I'd just return an Array containing all the output values of the function. Or make the mutable values instance variables in an object and the function a method on that object.
Thanks for both answers.
It seems I came out with an equivalent solution at last : the mutable container.
I created a new class 'OutputParameter' that contains (as attr_accessors) the parameters that I want to output from my method. Then I passed an instance of this class to my method.
class OutputParameters
attr_accessor :order_id, pizza
end
class RestaurantController < ApplicationController
def pizza_to_deliver(pizza_name, output_parameters)
# pizza to eat
pizza = Pizza.where(:name => pizza_name).first
# unknown pizza
return false if pizza.nil?
# first customer order about this pizza
id_of_the_order = Orders.where(:pizza_id => pizza.id).first
# Output values returned
output_parameters.pizza = pizza
output_parameters.order_id = id_of_the_order
true
end
end
my_pizza_name = 'margerita'
my_output = OutputParameters.new
my_restaurant = RestaurantController.new
if my_restaurant.pizza_to_deliver(my_pizza_name, my_output) then
puts "Pizza to deliver : #{my_output.order_id}"
rex_dog.eat(my_output.pizza)
end
The hash or array you suggested seems even a better idea as it is more adaptative : I wouldn't have to declare a class.
I would just use the merge! method
class RestaurantController < ApplicationController
def pizza_to_deliver(pizza_name, output_hash)
# pizza to eat
pizza = Pizza.where(:name => pizza_name).first
# unknown pizza
return false if pizza.nil?
# first customer order about this pizza
id_of_the_order = Orders.where(:pizza_id => pizza.id).first
# Output values returned
output_hash.merge!({:pizza => pizza})
output_hash.merge!({:id_of_the_order => id_of_the_order})
true
end
end
my_pizza_name = 'margerita'
my_output_hash = {}
my_restaurant = RestaurantController.new
if my_restaurant.pizza_to_deliver(my_pizza_name, my_output_hash) then
puts "Pizza to deliver : #{my_output_hash[:id_of_the_order]}"
rex_dog.eat(my_output_hash[:pizza])
end
You could use multiple return values like this:
def maybe_get_something
...
return nil, "sorry" if bad_condition
...
something, nil
end
...
something, err = maybe_get_something
if !err.nil?
handle(err)
return
end
do_something_with(something)
Very similar to what people do when using Go:
f, err := os.Open("filename.ext")
if err != nil {
log.Fatal(err)
}
// do something with the open *File f

How can I write better code for passing key-value arguments?

I want to write code for Ruby in a more Ruby-like style and ran into a problem when working with argument passing.
I have to see if ABC is nil or not. If ABC is nil, I would pass another symbol into dosomething, if not I would pass another type of hash value to compute.
Since Ruby is not like Java, it can pass a different type of argument (different keys).
How can I make the following code more beautiful?
Merging do_manything, do_otherthings, do_manythings_again into a single function is not the answer I because I would call dosomething in many places in my code:
if ABC.nil?
Apple.dosomething (:foo => DEF) { |a|
a.do_manything
a.do_otherthings
a.do_manythings_again
}
else
Apple.dosomething (:bar => ABC) { |a|
a.do_manything
a.do_otherthings
a.do_manythings_again
}
end
Using the ternary operator.
Apple.dosomething (ABC.nil? ? {foo:DEF} : {bar:ABC}) do |a|
a.do_manything
a.do_otherthings
a.do_manythings_again
end
Here is the format
condition ? return_if_true : return_if_false
You can either switch the hash you send:
opts = ABC.nil? ? {foo:DEF} : {bar:ABC}
Apple.dosomething(opts) do |a|
do_many_things
do_other_things
do_many_things_again
end
...or you can pass a lambda as the block:
stuff_to_do = ->(a) do
do_many_things
do_other_things
do_many_things_again
end
if ABC.nil?
Apple.dosomething(foo:DEF,&stuff_to_do)
else
Apple.dosomething(bar:ABC,&stuff_to_do)
end
You could do this:
options = if ABC.nil? then { foo: DEF } else { bar: ABC } end
Apple.do_something options do |apple|
apple.instance_eval do
do_many_things
do_other_things
do_many_things_again
end
end
By convention, words in names and identifiers are separated by underscores (_) and do/end is used for multiple-line blocks.
Also, I believe this question belongs on Code Review.

Ruby - What is this output

I know that this code may be not quite correct:
def print_string(&str)
puts str
end
print_string{"Abder-Rahman"}
But, when I run it, this is what I get:
#<Proc:0x03e25d98#r.rb:5>
What is this output?
That's the default string representation of a Proc object. Because "Abder-Rahman" is in braces, Ruby thinks you're defining a block. Did you mean to put str.call inside of your function definition? That should call your block and return the string expression you defined inside it.
The problem is that you've declared that the "print_string" method takes a block argument (confusingly named "str") and you simply print the proc itself. You'd probably like to call the given procedure to see the string value it returns:
def call_proc(&proc)
proc.call
end
call_proc { 'Foobar' }
# => "Foobar"
What you've discovered is the syntax sugar that if you decorate the last argument of a method definition with an ampersand & then it will be bound to the block argument to the method call. An alternative way of accomplishing the same task is as follows:
def call_proc2
yield if block_given?
end
call_proc2 { 'Example' }
# => 'Example'
Note also that procedures can be handled directly as objects by using Proc objects (or the "lambda" alias for the Proc constructor):
p1 = Proc.new { 'Foo' }
p1.call # => "Foo"
p2 = lambda { 'Bar' }
p2.call # => "Bar"
You're passing a block to the method, as denoted by the & prefix and how you're calling it. That block is then converted into a Proc internally.
puts str.call inside your method would print the string, although why you'd want to define the method this way is another matter.
See Proc:
http://www.ruby-doc.org/core/classes/Proc.html
When the last argument of function/method is preceded by the & character, ruby expect a proc object. So that's why puts's output is what it is.
This blog has an article about the unary & operator.

Stepping into Ruby Meta-Programming: Generating proxy methods for multiple internal methods

I've multiply heard Ruby touted for its super spectacular meta-programming capabilities, and I was wondering if anyone could help me get started with this problem.
I have a class that works as an "archive" of sorts, with internal methods that process and output data based on an input. However, the items in the archive in the class itself are represented and processed with integers, for performance purposes. The actual items outside of the archive are known by their string representation, which is simply number_representation.to_s(36).
Because of this, I have hooked up each internal method with a "proxy method" that converts the input into the integer form that the archive recognizes, runs the internal method, and converts the output (either a single other item, or a collection of them) back into strings.
The naming convention is this: internal methods are represented by _method_name; their corresponding proxy method is represented by method_name, with no leading underscore.
For example:
class Archive
## PROXY METHODS ##
## input: string representation of id's
## output: string representation of id's
def do_something_with id
result = _do_something_with id.to_i(36)
return nil if result == nil
return result.to_s(36)
end
def do_something_with_pair id_1,id_2
result = _do_something_with_pair id_1.to_i(36), id_2.to_i(36)
return nil if result == nil
return result.to_s(36)
end
def do_something_with_these ids
result = _do_something_with_these ids.map { |n| n.to_i(36) }
return nil if result == nil
return result.to_s(36)
end
def get_many_from id
result = _get_many_from id
return nil if result == nil # no sparse arrays returned
return result.map { |n| n.to_s(36) }
end
## INTERNAL METHODS ##
## input: integer representation of id's
## output: integer representation of id's
private
def _do_something_with id
# does something with one integer-represented id,
# returning an id represented as an integer
end
def do_something_with_pair id_1,id_2
# does something with two integer-represented id's,
# returning an id represented as an integer
end
def _do_something_with_these ids
# does something with multiple integer ids,
# returning an id represented as an integer
end
def _get_many_from id
# does something with one integer-represented id,
# returns a collection of id's represented as integers
end
end
There are a couple of reasons why I can't just convert them if id.class == String at the beginning of the internal methods:
These internal methods are somewhat computationally-intensive recursive functions, and I don't want the overhead of checking multiple times at every step
There is no way, without adding an extra parameter, to tell whether or not to re-convert at the end
I want to think of this as an exercise in understanding ruby meta-programming
Does anyone have any ideas?
edit
The solution I'd like would preferably be able to take an array of method names
##PROXY_METHODS = [:do_something_with, :do_something_with_pair,
:do_something_with_these, :get_many_from]
iterate through them, and in each iteration, put out the proxy method. I'm not sure what would be done with the arguments, but is there a way to test for arguments of a method? If not, then simple duck typing/analogous concept would do as well.
I've come up with my own solution, using #class_eval
##PROXY_METHODS.each do |proxy|
class_eval %{ def #{proxy} *args
args.map! do |a|
if a.class == String
a.to_i(36)
else
a.map { |id| id.to_i(36) }
end
end
result = _#{proxy}(*args)
result and if result.respond_to?(:each)
result.map { |r| r.to_s(36) }
else
result.to_s(36)
end
end
}
end
However, #class_eval seems a bit...messy? or inelegant compared to what it "should" be.
class Archive
# define a new method-creating method for Archive by opening the
# singleton class for Archive
class << Archive
private # (make it private so no one can call Archive.def_api_method)
def def_api_method name, &defn
define_method(name) do |*args|
# map the arguments to their integer equivalents,
# and pass them to the method definition
res = defn[ *args.map { |a| a.to_i(36) } ]
# if we got back a non-nil response,
res and if res.respond_to?(:each)
# map all of the results if many returned
res.map { |r| r.to_s(36) }
else
# map the only result if only one returned
res.to_s(36)
end
end
end
end
def_api_method("do_something_with"){ |id| _do_something_with(id) }
def_api_method("do_something_with_pair"){ |id_1, id_2| _do_something_with_pair id_1.to_i(36), id_2.to_i(36) }
#...
end
Instead of opening the singleton to define Archive.def_api_method, you could define it simply using
class Archive
def Archive.def_api_method
#...
But the reason I didn't do that is then anyone with access to the Archive class could invoke it using Archive.def_api_method. Opening up the singleton class allowed me to mark def_api_method as private, so it can only be invoked when self == Archive.
If you're always going to be calling an internal version with the same (or derivable) name, then you could just invoke it directly (rather than pass a definition block) using #send.
class Archive
# define a method-creating method that wraps an internal method for external use
class << Archive
private # (make it private so no one can call Archive.api_method)
def api_method private_name
public_name = private_name.to_s.sub(/^_/,'').to_sym
define_method(public_name) do |*args|
# map the arguments to their integer equivalents,
# and pass them to the private method
res = self.send(private_name, *args.map { |a| a.to_i(36) })
# if we got back a non-nil response,
res and if res.respond_to?(:each)
# map all of the results if many returned
res.map { |r| r.to_s(36) }
else
# map the only result if only one returned
res.to_s(36)
end end
# make sure the public method is publicly available
public public_name
end
end
api_method :_do_something_with
api_method :_do_something_with_pair
private
def _do_something_with
#...
end
def _do_something_with_pair
#...
end
end
This is more like what is done by other meta-methods like attr_reader and attr_writer.

Resources