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
Explicit return Ruby provides a keyword that allows the developer to explicitly stop the execution flow of a method and return a specific value.
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.
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].
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.
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
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