Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`return` in Ruby Array#map

I have a method where I would like to decide what to return within a map function. I am aware that this can be done with assigning a variable, but this is how I though I could do it;

def some_method(array)     array.map do |x|       if x > 10          return x+1 #or whatever       else          return x-1       end     end end 

This does not work as I expect because the first time return is hit, it returns from the method, and not in the map function, similar to how the return is used in javascript's map function.

Is there a way to achieve my desired syntax? Or do I need to assign this to a variable, and leave it hanging at the end like this:

def some_method(array)     array.map do |x|       returnme = x-1       if x > 10          returnme = x+1 #or whatever       end       returnme     end end 
like image 588
Automatico Avatar asked Sep 06 '16 13:09

Automatico


People also ask

What is return in Ruby?

Explicit return Ruby provides a keyword that allows the developer to explicitly stop the execution flow of a method and return a specific value.

How do I return an index to an array in Ruby?

Ruby | Array class find_index() operation Array#find_index() : find_index() is a Array class method which returns the index of the first array. If a block is given instead of an argument, returns the index of the first object for which the block returns true.

Does each return an array Ruby?

It's basically a "free" operation for Ruby to return the original array (otherwise it would return nil ). As a bonus it allows you to chain methods to further operate on the array if you want. A small point: if no block is present, [1,2,3]. each returns [1,2,3].

How do you return the number of elements in an array in Ruby?

Ruby | Array count() operation Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.


1 Answers

Sergio's answer is very good, but it's worth pointing out that there is a keyword that works the way you wanted return to work: next.

array.map do |x|   if x > 10     next x + 1   else     next x - 1   end end 

This isn't a very good use of next because, as Sergio pointed out, you don't need anything there. However, you can use next to express it more explicitly:

array.map do |x|   next x + 1 if x > 10   x - 1 end 
like image 63
Jordan Running Avatar answered Oct 02 '22 11:10

Jordan Running