Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to write a bang method, like map?

Tags:

ruby

self

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!

like image 854
wulftone Avatar asked Oct 05 '11 17:10

wulftone


People also ask

How do you create a map in Ruby?

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.

How do you use the map method in Ruby?

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.

What is the difference between collect and map in Ruby?

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.

What does &: mean in Ruby?

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.


2 Answers

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]
like image 112
Gazler Avatar answered Sep 20 '22 05:09

Gazler


def stuff!
  self.something = 'something else'
end

bam, you've modified the underlying object without returning a new object

like image 44
Jimmy Avatar answered Sep 20 '22 05:09

Jimmy