When to use (:method) or (&:method) - ruby

Why does: respond_to? in:
class Wolf
def howl; end
end
Wolf.new.respond_to?(:howl) # => true
not require & while map in:
["1", "2", "3"].map(&:to_i) # => [1, 2, 3]
does? Also, are there any technical names for this?

When you say :method, you're using some nice syntactical sugar in ruby that creates a new Symbol object. When you throw an ampersand before it (&:method), you're using another piece of sugar. This invokes the to_proc method on the symbol.
So, these two things are identical:
method_proc = &:method
sym = :method
method_proc = method.to_proc
What's the difference between that and the other usage? Well, respond_to? has a single argument -- a symbol. So we can pass :method and be all fine and dandy. (Interestingly, objects do respond to the method named method, but that's a far more confusing question).
By comparison, Enumerable's iterators (like map, select, etc) accept a block. When we pass a Proc, it is interpreted properly as that block. So, these two pieces of code are equivalent:
[1,2,3].map { |i| i.even? }
[1,2,3].map(&:even?)
This equivalence is a little confusing, because of course Symbol has no idea that there's an even? method somewhere. To play around with it, I used evenproc = :even?.to_proc to inspect the resulting proc. It's implemented in C (at least in MRI ruby), and isn't willing to give up its source. However, its arity is -1, which means that it accepts one optional arg. My best guess is that it does something like this:
def to_proc
method_name = self.to_s
->(a) { a.send(method_name) }
end
I could dig further, but I think we've already gone way past the question. ;) Good luck!

Related

Omitting an argument for a method in a block

I wonder, is it possible to do something similar in Ruby to what I can do in Scala or other languages:
someCollection.foreach(x => println(x)) // a full version
someCollection.foreach(println) // a short version
In Ruby I can do:
some_array.each { |x| puts x }
So how can I do this?
some_array.each { puts }
UPDATE:
I'm not talking about puts in particular, it just picked it for example. There might be some_other_method which takes one parameter.
some_array.map { some_other_method }
some_array.map(some_other_method) # ???
def some_other_method a
# ... doing something with a
end
If you look up the rules for implicit η-expansion in the SLS (§6.26.5), it should be immediately obvious that it relies crucially on static type information and thus cannot possibly work in Ruby.
You can, however, explicitly obtain a Method object via reflection. Method objects respond to to_proc and like any object that responds to to_proc can thus be passed as if they were blocks using the unary prefix & operator:
some_array.each(&method(:puts))
Not quite like that, unfortunately. You can send a method name to be called on each object, e.g.:
some_array.each &:print_myself
Which is equivalent to:
some_array.each {|x| x.print_myself}
But I don't know of a clean (read: built-in) way to do what you're asking for. (Edit: #Jörg's answer does this, though it doesn't really save you any typing. There is no automatic partial function application in Ruby)

What does to_proc method mean in Ruby?

I am learning rails and following this thread. I am stuck with the to_proc method. I consider symbols only as alternatives to strings (they are like strings but cheaper in terms of memory). If there is anything else I am missing for symbols, then please tell me. Please explain in a simple way what to_proc means and what it is used for.
Some methods take a block, and this pattern frequently appears for a block:
{|x| x.foo}
and people would like to write that in a more concise way. In order to do that they use a combination of: a symbol, the method Symbol#to_proc, implicit class casting, and & operator. If you put & in front of a Proc instance in the argument position, that will be interpreted as a block. If you combine something other than a Proc instance with &, then implicit class casting will try to convert that to a Proc instance using to_proc method defined on that object if there is any. In case of a Symbol instance, to_proc works in this way:
:foo.to_proc # => ->x{x.foo}
For example, suppose you write:
bar(&:foo)
The & operator is combined with :foo, which is not a Proc instance, so implicit class cast applies Symbol#to_proc to it, which gives ->x{x.foo}. The & now applies to this and is interpreted as a block, which gives:
bar{|x| x.foo}
The easiest way to explain this is with some examples.
(1..3).collect(&:to_s) #=> ["1", "2", "3"]
Is the same as:
(1..3).collect {|num| num.to_s} #=> ["1", "2", "3"]
and
[1,2,3].collect(&:succ) #=> [2, 3, 4]
Is the same as:
[1,2,3].collect {|num| num.succ} #=> [2, 3, 4]
to_proc returns a Proc object which responds to the given method by symbol.
So in the third case, the array [1,2,3] calls its collect method and. succ is method defined by class Array. So this parameter is a short hand way of saying collect each element in the array and return its successor and from that create a new array which results in [2,3,4]. The symbol :succ is being converted to a Proc object so it call the Array's succ method.
For me the clearest explanation is seeing a simple implementation of it. Here's what it might look like if I were reimplementing Symbol#to_proc:
class Symbol # reopen Symbol class to reimplement to_proc method
def to_proc
->(object) { object.send(self) }
end
end
my_lambda = :to_s.to_proc
puts my_lambda.(1) # prints '1'; .() does the same thing as .call()
puts my_lambda.(1).class # prints 'String'
puts [4,5,6].map(&:to_s) # prints "4\n5\n6\n"
puts [4,5,6].map(&:to_s).first.class # prints 'String'
For anybody still a bit stumped, running the following code might make things a little clearer:
class Symbol
def to_proc
proc do |obj|
puts "Symbol proc: #{obj}.send(:#{self})"
obj.send(self)
end
end
end
class Array
def map(&block)
copy = self.class.new
self.each do |index|
puts "Array.map: copy << block.call(#{index})"
copy << block.call(index)
end
copy
end
end
remapped_array = [0, 1, 2].map &:to_s
puts "remapped array: #{remapped_array.inspect}"
These are not the actual implementations of Symbol.to_proc or Array.map, they are just simplified versions which I'm using to demonstrate how map &:to_s and similar calls work.

Defining method in Ruby with equals

Being new to Ruby, I'm having trouble explaining to myself the behavior around method definitions within Ruby.
The example is noted below...
class Foo
def do_something(action)
action.inspect
end
def do_something_else=action
action.inspect
end
end
?> f.do_something("drive")
=> "\"drive\""
?> f.do_something_else=("drive")
=> "drive"
The first example is self explanatory. What Im trying to understand is the behavior of the second example. Other than what looks to be one producing a string literal and the other is not, what is actually happening? Why would I use one over the other?
Generally, do_something is a getter, and do_something= is a setter.
class Foo
attr_accessor :bar
end
is equivalent to
class Foo
def bar
#bar
end
def bar=(value)
#bar = value
end
end
To answer your question about the difference in behavior, methods that end in = always return the right hand side of the expression. In this case returning action, not action.inspect.
class Foo
def do_something=(action)
"stop"
end
end
?> f = Foo.new
?> f.do_something=("drive")
=> "drive"
Both of your methods are actually being defined and called as methods. Quite a lot of things in Ruby can be defined as methods, even the operators such as +, -, * and /. Ruby allows methods to have three special notational suffixes. I made that phrase up all by myself. What I mean by notational suffixes is that the thing on the end of the method will indicate how that method is supposed to work.
Bang!
The first notational suffix is !. This indicates that the method is supposed to be destructive, meaning that it modifies the object that it's called on. Compare the output of these two scripts:
a = [1, 2, 3]
a.map { |x| x * x }
a
And:
a = [1, 2, 3]
a.map! { |x| x * x }
a
There's a one character difference between the two scripts, but they operate differently! The first one will still go through each element in the array and perform the operation inside the block, but the object in a will still be the same [1,2,3] that you started with.
In the second example, however, the a at the end will instead be [1, 4, 9] because map! modified the object in place!
Query
The second notational suffix is ?, and that indicates that a method is used to query an object about something, and means that the method is supposed to return true, false or in some extreme circumstances, nil.
Now, note that the method doesn't have to return true or false... it's just that it'd be very nice if it did that!
Proof:
def a?
true
end
def b?
"moo"
end
Calling a? will return true, and calling b? will return "moo". So there, that's query methods. The methods that should return true or false but sometimes can return other things because some developers don't like other developers.
Setters!
NOW we get to the meat of your (paraphrased) question: what does = mean on the end of a method?
That usually indicates that a method is going to set a particular value, as Erik already outlined before I finished typing this essay of an answer.
However, it may not set one, just like the query methods may not return true or false. It's just convention.
You can call that setter method like this also:
foo.something_else="value"
Or (my favourite):
foo.something_else = "value"
In theory, you can actually ignore the passed in value, just like you can completely ignore any arguments passed into any method:
def foo?(*args)
"moo"
end
>> foo?(:please, :oh, :please, :why, :"won't", :you, :use, :these, :arguments, :i, :got, :just, :for, :you, :question_mark?)
=> "moo"
Ruby supports all three syntaxes for setter methods, although it's very rare to see the one you used!
Well, I hope this answer's been roughly educational and that you understand more things about Ruby now. Enjoy!
You cannot define a return value for assignment methods. The return value is always the same as the value passed in, so that assignment chains (x = y = z = 3) will always work.
Typically, you would omit the brackets when you invoke the method, so that it behaves like a property:
my_value = f.do_something= "drive"
def do_something_else=action
action.inspect
end
This defines a setter method, so do_something_else appears as though we are initializing a attribute. So the value initialized is directly passed,

Named arguments as local variables in Ruby

I find myself constantly writing what I see as unnecessary code in Ruby when using named arguments for methods.
Take for example the following code:
def my_method(args)
orange = args[:orange]
lemon = args[:lemon]
grapefruit = args[:grapefruit]
# code that uses
# orange, lemon & grapefruit in this format which is way prettier & concise than
# args[:orange] args[:lemon] args[:grapefruit]
puts "my_method variables: #{orange}, #{lemon}, #{grapefruit}"
end
my_method :orange => "Orange", :grapefruit => "Grapefruit"
What I really don't like about this code is that I am having to take the args and pass the values into local variables going against DRY principles and just generally taking up space in my methods. And if I don't use local variables and just refer to all variables with the args[:symbol] syntax then the code becomes somewhat illegible.
I have tried working up a solution to this but keeping hitting a brick wall as I don't know how to define local variables using eval in the scope of the method, or using any other technique. Here is one of many attempts below, which results in an error
def my_method_with_eval(args)
method_binding = binding
%w{ orange lemon grapefruit}.each { |variable| eval "#{variable} = args[:#{variable}]", method_binding; }
# code that uses
# orange, lemon & grapefruit in this format which is way prettier & concise than
# args[:orange] args[:lemon] args[:grapefruit]
puts "my_method_with_eval variables: #{orange}, #{lemon}, #{grapefruit}"
end
my_method_with_eval :orange => "Orange", :grapefruit => "Grapefruit"
When running that code I simply get
NameError: undefined local variable or method ‘orange’ for main:Object method my_method_with_eval in named_args_to_local_vars at line at top level in named_args_to_local_vars at line 9
Anyone got any ideas how I could simplify this down somehow so that I don't have to start my named argument methods with loads of var=args[:var] code?
Thanks,
Matthew O'Riordan
I don't believe there's any way to do this in Ruby (if anyone comes up with one, please let me know, and I'll update or delete this answer to reflect it!) - if a local variable hasn't been defined yet, there's no way to dynamically define it with the binding. You could conceivably do something like orange, lemon, grapefruit = nil before calling eval, but you may run into other problems - for instance, if args[:orange] is the string "Orange", you'll end up evaluating orange = Orange with your current implementation.
Here's something that could work, though, using the OpenStruct class from the standard library (by "could work", I mean "it's up to your sense of style whether a.orange is any nicer than args[:orange]"):
require 'ostruct'
def my_method_with_ostruct(args)
a = OpenStruct.new(args)
puts "my_method_with_ostruct variables: #{a.orange}, #{a.lemon}, #{a.grapefruit}"
end
If you don't need easy access to any state or methods on the receiver of this method, you could use instance_eval, as follows.
def my_method_with_instance_eval(args)
OpenStruct.new(args).instance_eval do
puts "my_method_with_instance_eval variables: #{orange}, #{lemon}, #{grapefruit}"
end
end
You could even do something tricky with method_missing (see here for more) to allow access to the "primary" object, but the performance probably wouldn't be great.
All in all, I think it's probably most straightforward/readable to go with the less DRY initial solution that bothered you.
Merge of Greg's and Sand's answers:
require 'ostruct'
def my_method(args = {})
with args do
puts a
puts b
end
end
def with(args = {}, &block)
OpenStruct.new(args).instance_eval(&block)
end
my_method(:a => 1, :b => 2)
I found a discussion on this on ruby-talk-google and it seems to be an optimisation of the parser. Local variables are already figured out at runtime so that local_variables is already set at the beginning of the method.
def meth
p local_variables
a = 0
p local_variables
end
meth
# =>
[:a]
[:a]
That way Ruby doesn’t need to decide whether a is a method or a local variable or whatnot at runtime but can safely assume it is a local variable.
(For comparison: In Python locals() would be empty at the beginning of the function.)
At my blog (see link in user info), I just tried to address handling this problem neatly. I go into more detail there, but the core of my solution is the following helper method:
def collect_named_args(given, expected)
# collect any given arguments that were unexpected
bad = given.keys - expected.keys
# if we have any unexpected arguments, raise an exception.
# Example error string: "unknown arguments sonething, anyhting"
raise ArgumentError,
"unknown argument#{bad.count > 1 ? 's' : ''}: #{bad.join(', ')}",
caller unless bad.empty?
Struct.new(*expected.keys).new(
*expected.map { |arg, default_value|
given.has_key?(arg) ? given[arg] : default_value
}
)
end # def collect_named_args
which is called as follows:
def foo(arguments = {})
a = collect_named_args(arguments,
something: 'nothing',
everything: 'almost',
nothing: false,
anything: 75)
# Do something with the arguments
puts a.anything
end # def foo
I'm still trying to figure out if there is any way to get my results into local_variables or not - but as others have noted, Ruby doesn't want to do that. You could use the "with" trick, I suppose.
module Kernel
def with(object, &block)
object.instance_eval &block
end
end
then
with(a) do
# Do something with arguments (a)
put anything
end
but that feels unsatisfactory for several reasons.
I like the above solution because it uses a Struct instead of an OpenStruct, which means one less require, and what you get back is set as far as what variables are being handled.
This doesn't solve the problem, but I tend to do
orange, lemon, grapefruit = [:orange, :lemon, :grapefruit].
map{|key| args.fetch(key)}
as it's pretty easy to copy and paste the orange lemon grapefruit bit.
If you find the colons too much work, you could do
orange, lemon, grapefruit = %w{orange, lemon, grapefruit}.
map{|str| str.gsub(",", "").to_sym}.map{|key| args.fetch(key)}
I found myself wondering how to do this myself today. Not only would I like to DRY up my code, but I'd like to have argument validation, too.
I came across a blog post by Juris Galang where he's explained a couple ways of handling it. He's has published a gem that encapsulates his ideas which looks interesting.

Elegant way of duck-typing strings, symbols and arrays?

This is for an already existing public API that I cannot break, but I do wish to extend.
Currently the method takes a string or a symbol or anything else that makes sense when passed as the first parameter to send
I'd like to add the ability to send a list of strings, symbols, et cetera. I could just use is_a? Array, but there are other ways of sending lists, and that's not very ruby-ish.
I'll be calling map on the list, so the first inclination is to use respond_to? :map. But a string also responds to :map, so that won't work.
How about treating them all as Arrays? The behavior you want for Strings is the same as for an Array containing only that String:
def foo(obj, arg)
[*arg].each { |method| obj.send(method) }
end
The [*arg] trick works because the splat operator (*) turns a single element into itself or an Array into an inline list of its elements.
Later
This is basically just a syntactically sweetened version or Arnaud's answer, though there are subtle differences if you pass an Array containing other Arrays.
Later still
There's an additional difference having to do with foo's return value. If you call foo(bar, :baz), you might be surprised to get [baz] back. To solve this, you can add a Kestrel:
def foo(obj, arg)
returning(arg) do |args|
[*args].each { |method| obj.send(method) }
end
end
which will always return arg as passed. Or you could do returning(obj) so you could chain calls to foo. It's up to you what sort of return-value behavior you want.
A critical detail that was overlooked in all of the answers: strings do not respond to :map, so the simplest answer is in the original question: just use respond_to? :map.
Since Array and String are both Enumerables, there's not an elegant way to say "a thing that's an Enumberable, but not a String," at least not in the way being discussed.
What I would do is duck-type for Enumerable (responds_to? :[]) and then use a case statement, like so:
def foo(obj, arg)
if arg.respond_to?(:[])
case arg
when String then obj.send(arg)
else arg.each { |method_name| obj.send(method_name) }
end
end
end
or even cleaner:
def foo(obj, arg)
case arg
when String then obj.send(arg)
when Enumerable then arg.each { |method| obj.send(method) }
else nil
end
end
Perhaps the question wasn't clear enough, but a night's sleep showed me two clean ways to answer this question.
1: to_sym is available on String and Symbol and should be available on anything that quacks like a string.
if arg.respond_to? :to_sym
obj.send(arg, ...)
else
# do array stuff
end
2: send throws TypeError when passed an array.
begin
obj.send(arg, ...)
rescue TypeError
# do array stuff
end
I particularly like #2. I severely doubt any of the users of the old API are expecting TypeError to be raised by this method...
Let's say your function is named func
I would make an array from the parameters with
def func(param)
a = Array.new
a << param
a.flatten!
func_array(a)
end
You end up with implementing your function func_array for arrays only
with func("hello world") you'll get a.flatten! => [ "hello world" ]
with func(["hello", "world"] ) you'll get a.flatten! => [ "hello", "world" ]
Can you just switch behavior based on parameter.class.name? It's ugly, but if I understand correctly, you have a single method that you'll be passing multiple types to - you'll have to differentiate somehow.
Alternatively, just add a method that handles an array type parameter. It's slightly different behavior so an extra method might make sense.
Use Marshal to serialize your objects before sending these.
If you don't want to monkeypatch, just massage the list to an appropriate string before the send. If you don't mind monkeypatching or inheriting, but want to keep the same method signature:
class ToBePatched
alias_method :__old_takes_a_string, :takes_a_string
#since the old method wanted only a string, check for a string and call the old method
# otherwise do your business with the map on things that respond to a map.
def takes_a_string( string_or_mappable )
return __old_takes_a_string( string_or_mappable ) if String === string_or_mappable
raise ArgumentError unless string_or_mappable.responds_to?( :map )
# do whatever you wish to do
end
end
Between those 3 types I'd do this
is_array = var.respond_to?(:to_h)
is_string = var.respond_to?(:each_char)
is_symbol = var.respond_to?(:to_proc)
Should give a unique answer for [], :sym, 'str'

Resources