I'd like to write some new Array methods that alter the calling object, like so:
a = [1,2,3,4]
a.map!{|e| e+1}
a = [2,3,4,5]
...but I'm blanking on how to do this. I think I need a new brain.
So, I'd like something like this:
class Array
def stuff!
# change the calling object in some way
end
end
map! is just an example, I'd like to write a completely fresh one without using any pre-existing ! methods.
Thanks!
Ruby Map SyntaxFirst, you have an array, but it could also be a hash, or a range. Then you call map with a block. The block is this thing between brackets { ... } . Inside the block you say HOW you want to transform every element in the array.
The way the map method works in Ruby is, it takes an enumerable object, (i.e. the object you call it on), and a block. Then, for each of the elements in the enumerable, it executes the block, passing it the current element as an argument. The result of evaluating the block is then used to construct the resulting array.
There's no difference, in fact map is implemented in C as rb_ary_collect and enum_collect (eg. there is a difference between map on an array and on any other enum, but no difference between map and collect ). Why do both map and collect exist in Ruby? The map function has many naming conventions in different languages.
In a method argument list, the & operator takes its operand, converts it to a Proc object if it isn't already (by calling to_proc on it) and passes it to the method as if a block had been used.
EDIT - Updated answer to reflect the changes to your question.
class Array
def stuff!
self[0] = "a"
end
end
foo = [1,2,3,4]
foo.stuff!
p foo #=> ['a',2,3,4]
def stuff!
self.something = 'something else'
end
bam, you've modified the underlying object without returning a new object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With