I'm learning about the unary operator, &
.
There are some great questions about using &
in the parameters of a method invocation. Usually the format goes something like some_obj.some_method(&:symbol)
:
- Ruby unary operator
&
only valid on method arguments - What is the functionality of “&: ” operator in ruby?
- What does map(&:name) mean in Ruby?
- Unary Ampersand Operator and passing procs as arguments in Ruby
It seems like the main idea is ruby calls the to_proc
method on :symbol
when the unary operator is placed in front of the symbol. Because Symbol#to_proc
exists "everything works".
I'm still confused about how everything just works.
What if I want to implement a "to_proc sort of functionality with a string". I'm putting it in quotes because I'm not really sure how to even talk about what I'm trying to do.
But the goal is to write a String#to_proc
method such that the following works:
class String
def to_proc # some args?
Proc.new do
# some code?
end
end
end
p result = [2, 4, 6, 8].map(&'to_s 2')
#=> ["10", "100", "110", "1000"]
This is how I did it:
class String
def to_proc
Proc.new do |some_arg|
parts = self.split(/ /)
some_proc = parts.first.to_sym.to_proc
another_arg = parts.last.to_i
some_proc.call(some_arg, another_arg)
end
end
end
p result = [2, 4, 6, 8].map(&'to_s 2')
#=> ["10", "100", "110", "1000"]
The main part I'm confused about is how I get the parameters into the String#to_proc
method. It seems like:
def to_proc
Proc.new do |some_arg| ...
end
Should be:
def to_proc some_arg
Proc.new do |yet_another_arg| ...
end
Or something like that. How do the [2, 4, 6, 8]
values get into the proc that String#to_proc
returns?