ruby - How to create a custom while block -


i know in ruby can use while loop, want know if can create custom 1 can make this:

custom_while < 5     puts     += 1 end 

i have code:

def custom_while(condition)     loop         break if not condition         yield     end end  = 0 custom_while < 5     puts     += 1 end 

however, when condition evaluated, true (because considers first evaluation of i < 5 = true only.

any appreciated!

note: educational purposes only.

you had it. so, problem condition evaluated once? well, construct know can evaluate want? that's right: functions! so, let's make condition function (or proc in ruby lingo):

def custom_while(condition)   loop     break unless condition.()     yield   end end  = 0 custom_while -> { < 5 }   puts   += 1 end # 0 # 1 # 2 # 3 # 4 

this unfortunately not nice looking in other languages. ruby's syntax , semantics aggressively optimized methods take 1 "function" argument. ruby has special syntactically , semantically light-weight construct that, namely blocks. have more one, though, you're out of luck.

compare languages have proper block literals, smalltalk, example. in smalltalk, write method while:do:, , call this:

i := 0. while: [i < 5] do: [transcript write: i. := + 1]. 

in fact, in smalltalk, syntax blocks lightweight there no control structures @ in language. if/then/else instance method of boolean, example:

i % 2 == 0 iftrue: [transcript write: "even"] iffalse: [transcript write: "odd"]. 

and while instance method of block, in reality, example this:

i := 0. [i < 5] whiletrue: [transcript write: i. := + 1] 

note: make no guarantees smalltalk code, didn't test it.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -