How can I map an array in ruby? - ruby

I have an array of integers
a = [3, 4, 5, 6]
and I need to POW this numbers, so they can be like this
a
# => [9, 16, 25, 36]
I'm trying to do this with this piece of code:
a.map!(&:**2)
but Isn't working :(
Can anyone help me?

You can use a lambda with & if you so desire:
square = lambda { |x| x**2 }
a.map!(&square)
This sort of thing is pointless busywork with a block so simple but it can be nice if you have a chain of such things and the blocks are more complicated:
ary.select(&some_complicated_criteria)
.map(&some_mangling_that_takes_more_than_one_line)
...
Collecting bits of logic in lambdas so that you can name the steps has its uses.

You should do this
a.map! { |i| i**2 }
Read the docs.

As a matter of rule, you cannot add parameters to methods using the &:sym syntax.
However, if you follow my suggestion here you could do the following:
class Symbol
def with(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
end
a.map!(&:**.with(2))
# => [9, 16, 25, 36]

You can only use the &: shortcut syntax if you are calling a method on the object with no arguments. In this case, you need to pass 2 as an argument to the ** method.
Instead, expand the block to the full syntax
a.map! { |n| n**2 }

Related

Is there a default block argument in Ruby?

I am just starting to do Groovy after mostly doing ruby.
It has a default 'block argument', it, as it were, not officially the terminology for Groovy, but I'm new to Groovy.
(1..10).each {println(it)}
What about Ruby? Is there a default I can use so I don't have to make |my_block_arg| every time?
Thanks!
No, you don't have a "default" in Ruby.
Though, you can do
(1..10).each(&method(:puts))
Like Andrey Deinekos answer explained there is no default. You can set the self context using BasicObject#instance_eval or BasicObject#instance_exec. I don't recommend doing this since it can sometimes result in some unexpected results. However if you know what you're doing the following is still an option:
class Enumerator
def with_ie(&block)
return to_enum(__method__) { each.size } unless block_given?
each { |e| e.instance_eval(&block) }
end
end
(1..10).each.with_ie { puts self }
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
#=> 1..10
(1..10).map.with_ie { self * self }
#=> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
(-5..5).select.with_ie { positive? }
#=> [1, 2, 3, 4, 5]
If you want to call one method you might as well do (-5..5).select(&:positive?), but when the objects you're iterating over have actual attributes it might be worth the trouble. For example:
people.map.with_ie { "#{id}: #{first_name} - #{last_name}" }
Keep in mind that if you have an local variable id, first_name or last_name in scope those are used instead of the methods on the object. This also doesn't quite work for hashes or Enumerable methods that pass more than one block argument. In this case self is set to an array containing the arguments. For example:
{a: 1, b: 2}.map.with_ie { self }
#=> [[:a, 1], [:b, 2]]
{a: 1, b: 2}.map.with_ie { self[0] }
#=> [:a, :b]
From Ruby 2.7 onwards, you can use numbered block arguments:
(1..10).each { puts _1 }
Granted, this hasn't been very well documented; some references are still using #1, but the above is tested on the official 2.7 version.

Implement to_s(2) with String#to_proc in Ruby

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?
Just write this
[2, 4, 6, 8].map { |each| each.to_s(2) }
Though I guess that is not what you're looking for …
Here is how Symbol#to_proc is implemented.
class Symbol
def to_proc
proc { |each| each.send(self) }
end
end
If you want you can define to_proc on an Array as follows
class Array
def to_proc
symbol, *args = self
proc { |each| each.send(symbol, *args) }
end
end
And then use
[2, 4, 6, 8].map(&[:to_s, 2])
Another alternative is using curry.
Though that does not work with bound methods, so you'll have to define a to_s lambda function first.
to_s = lambda { |n, each| each.to_s(n) }
[2, 4, 6, 8].map(&to_s.curry[2])
Though all of that seems more like academic exercises.
When you run some_method(&some_obj), Ruby first call the some_obj.to_proc to get a proc, then it "converts" that proc to a block and passes that block to some_method. So how the arguments go into the proc depends on how some_method passes arguments to the block.
For example, as you defined String#to_proc, which returns a proc{|arg| ...} (a proc with one argument), and calls [...].map(&'to_s 2'), Ruby interprets it as
[...].map(&('to_s 2'.to_proc))
which is
[...].map(&proc{|arg| ... })
and finally
[...].map {|arg| ... }
The problem with your approach is that there's no way to deduce the type of the argument when it's always passed as a string.
By the way, to address your question:
How do the [2, 4, 6, 8] values get into the proc that String#to_proc returns?
They are some_arg here, which is not a variable you have to define but instead is a parameter that is automatically passed when the proc is called.
Here's a rewriting of the String patch and some usage examples:
class String
def to_proc
fn, *args = split ' '
->(obj) { obj.send(fn.to_sym, *args) }
end
end
This works for the following example:
p result = [[1,2,3]].map(&"join -")
# => ['1-2-3']
but fails for this (your example):
p result = [2, 4, 6, 8].map(&'to_s 2')
# => TypeError
The problem is to_s('2') is being called, when the 2 should be an integer, not a string. I can't think of any way to get around this except for maybe some serialization (although one of the other answers shows how eval can work).
Now that the limitations of this approach are clear, it's worth comparing it to the more commonly used patch on Symbol to enable argument passing to proc shorthands (this taken from can-you-supply-arguments-to-the-mapmethod-syntax-in-ruby)
class Symbol
def call(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
end
a = [1,3,5,7,9]
a.map(&:+.(2))
# => [3, 5, 7, 9, 11]
This way you can pass any type of arguments to the proc, not just strings.
Once you've defined it, you can easily swap out String for Symbol:
class String
def call(*args, &blk)
to_sym.call(*args, &blk)
end
end
puts [1,2,3].map(&'+'.(1))
Refactored code
You're free to choose the name for the proc block variable. So it could be yet_another_arg, some_arg or something_else. In this case, the object you're passing to to_proc is actually the object you want to receive the proc call, so you could call it receiver. The method and param are in the String, so you get them with String#split from self.
class String
def to_proc
proc do |receiver|
method_name, param = self.split
receiver.method(method_name.to_sym).call(param.to_i)
end
end
end
p result = [2, 4, 6, 8].map(&'to_s 2')
# => ["10", "100", "110", "1000"]
Note that this method has been tailored to accept one method name and one integer argument. It doesn't work in the general case.
Another possibility
Warning
eval is evil
You've been warned
This works with the exact syntax you wanted, and it also works for a wider range of methods and parameters :
class String
def to_proc
proc { |x| eval "#{x.inspect}.#{self}" }
end
end
p [2, 4, 6, 8].map(&'to_s 2')
#=> ["10", "100", "110", "1000"]
p ["10", "100", "110", "1000"].map(&'to_i 2')
#=> [2, 4, 6, 8]
p [1, 2, 3, 4].map(&'odd?')
#=> [true, false, true, false]
p %w(a b c).map(&'*3')
#=> ["aaa", "bbb", "ccc"]
p [[1,2,3],[1,2],[1]].map(&'map(&"*2")')
#=> [[2, 4, 6], [2, 4], [2]]
It also brings security problems, though. With great power comes great responsibility!

Symbol#to_proc with parameters [duplicate]

This question already has answers here:
Can you supply arguments to the map(&:method) syntax in Ruby?
(9 answers)
Closed 8 years ago.
Given the following array a:
a = [1, 2, 3, 4, 5]
How do I do:
a.map { |num| num + 1 }
using the short notation:
a.map(&:+ 1)
or:
a.map(&:+ 2)
where 1 and 2 are the arguments?
In this case you can do
a.map(&1.method(:+))
But only because 1 + x is usually the same as x + 1.
Here is a discussion of this practice in a performance context.
You can't do it like this. The & operator is for turning symbols into procs.
a = [1, 2, 3, 4, 5]
puts a.map(&:to_s) # prints array of strings
puts a.map(&:to_s2) # error, no such method `to_s2`.
& is a shorthand for to_proc:
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
It creates and returns new proc. As you see, you can't pass any parameters to this method. You can only call the generated proc.
You cannot do it with map. But look at Facets' Enumerable#map_send:
require 'facets'
[1, 2, 3].map_send(:+, 1)
#=> [2, 3, 4]
Writing your own implementation is pretty straightforward:
module Enumerable
def map_send(*args)
map { |obj| obj.send(*args) }
end
end
If you really need that you can use Ampex library, but I don't know if it is still maintained.

Elegantly implementing 'map (+1) list' in ruby

The short code in title is in Haskell, it does things like
list.map {|x| x + 1}
in ruby.
While I know that manner, but what I want to know is, is there any more elegant manners to implement same thing in ruby like in Haskell.
I really love the to_proc shortcut in ruby, like this form:
[1,2,3,4].map(&:to_s)
[1,2,3,4].inject(&:+)
But this only accept exactly matching argument number between the Proc's and method.
I'm trying to seek a way that allow passing one or more arguments extra into the Proc, and without using an useless temporary block/variable like what the first demonstration does.
I want to do like this:
[1,2,3,4].map(&:+(1))
Does ruby have similar manners to do this?
If you just want to add one then you can use the succ method:
>> [1,2,3,4].map(&:succ)
=> [2, 3, 4, 5]
If you wanted to add two, you could use a lambda:
>> add_2 = ->(i) { i + 2 }
>> [1,2,3,4].map(&add_2)
=> [3, 4, 5, 6]
For arbitrary values, you could use a lambda that builds lambdas:
>> add_n = ->(n) { ->(i) { i + n } }
>> [1,2,3,4].map(&add_n[3])
=> [4, 5, 6, 7]
You could also use a lambda generating method:
>> def add_n(n) ->(i) { i + n } end
>> [1,2,3,4].map(&add_n(3))
=> [4, 5, 6, 7]
Use the ampex gem, which lets you use methods of X to build up any proc one one variable. Here’s an example from its spec:
["a", "b", "c"].map(&X * 2).should == ["aa", "bb", "cc"]
You can't do it directly with the default map. However it's quite easy to implement a version that supports this type of functionality. As an example Ruby Facets includes just such a method:
require 'facets/enumerable'
[1, 2, 3, 4].map_send(:+, 10)
=> [11, 12, 13, 14]
The implementation looks like this:
def map_send(meth, *args, &block)
map { |e| e.send(meth, *args, &block) }
end
In this particular case, you can use the following:
[1, 2, 3, 4].map(&1.method(:+))
However, this only works because + is not associative. It wouldn't work for -, for example.
Ruby hasn't built-in support for this feature, but you can create your own extension or use small gem 'ampex'. It defines global variable X with extended 'to_proc' functionality.
It gives you possibility to do that:
[1,2,3].map(&X.+(1))
Or even that:
"alpha\nbeta\ngamma\n".lines.map(&X.strip.upcase)
If you just want to add 1, you can use next or succ:
[1,2,3,4].map(&:next)
[1,2,3,4].map(&:succ)

How do I pass an argument to array.map short cut? [duplicate]

This question already has answers here:
Can you supply arguments to the map(&:method) syntax in Ruby?
(9 answers)
Closed 8 years ago.
Given the following array a:
a = [1, 2, 3, 4, 5]
How do I do:
a.map { |num| num + 1 }
using the short notation:
a.map(&:+ 1)
or:
a.map(&:+ 2)
where 1 and 2 are the arguments?
In this case you can do
a.map(&1.method(:+))
But only because 1 + x is usually the same as x + 1.
Here is a discussion of this practice in a performance context.
You can't do it like this. The & operator is for turning symbols into procs.
a = [1, 2, 3, 4, 5]
puts a.map(&:to_s) # prints array of strings
puts a.map(&:to_s2) # error, no such method `to_s2`.
& is a shorthand for to_proc:
def to_proc
proc { |obj, *args| obj.send(self, *args) }
end
It creates and returns new proc. As you see, you can't pass any parameters to this method. You can only call the generated proc.
You cannot do it with map. But look at Facets' Enumerable#map_send:
require 'facets'
[1, 2, 3].map_send(:+, 1)
#=> [2, 3, 4]
Writing your own implementation is pretty straightforward:
module Enumerable
def map_send(*args)
map { |obj| obj.send(*args) }
end
end
If you really need that you can use Ampex library, but I don't know if it is still maintained.

Resources