language features - Understanding Ruby Enumerable#map (with more complex blocks) -


Assume that I have a function

  def odd_or_even n if n% 2 == 0 Return: And also return: End of the weird end  

and I had a simple enumerable array

  simple = [1,2,3,4] , 5]  

And I run it through a map, with my work, using an end-end block:

  simple Map do | N | Odd_or_even (n) end # = & gt; [: Strange,: ,, strange, even:, weird]  

How can I do without it, say, define the ceremony in the first place? For example,

  # does not work smoothly. Map | N | | If n% 2 == 0 Return: More Return: Strange End End # Desired Results: # = & gt; [: Strange, even: weird, even: weird]  

is not a valid ruby, and to think about it the compiler gets mad with me . But how do I implement a similar type of work, which works?

edit

In fact, the solution to my problem is very low for me, compared to the motivation / logic behind it, helps me understand How the ruby ​​blocks work :)

Then just close the return Remove s and you become golden.

This is because the block has been sent to map (i.e. Proc.new ), and not a lambda within a proc < Code> return does not just exit the proc - this action jumps out of the method executed (i.e. call on) proc. A return within Lambda, on the other hand, only exits from Lambda.

proc Returns Lambda to Ruby 1.8, and gives a proxy in Ruby 1.9. It is probably best that you do not use this method and make clear about the way you want to build it.

I think you were trying it either in IRB or plain ruby ​​script.

  a = Proc.new {return} a.call # fails to return nothing from deaf foobar A = Proc.new {return} a.call 'hello' # # access Does not put The reason for the jump in the Pro to jump out of the Fubar method is the reason for execution. End Fobar # is successful, but 'Hello' does not print the return within the Pro jumps out of the method. B = lambda {return} b.call # is successful, return only returns from Lambda DEF BZUKUCKS B = LAMBDA {RETURN} BKLL puts 'Hello' # It reaches. Lambda had just returned from itself, finally Bezkux # succeeded, and printed 'Hello'  

To use this, use the underlying returns, unless you do so Can i think


Comments

Popular posts from this blog

windows - Heroku throws SQLITE3 Read only exception -

lex - Building a lexical Analyzer in Java -

python - rename keys in a dictionary -