Using Ruby to solve a quiz -
so found quiz on website excited solve newly acquired ruby skills (codeacademy, not quite finished yet).
what want make array 100 entries, set "open". then, planned create method containing loop iterates through every nth entry of array , changes either "open" or "closed", based on before. in loop, n should increased 1 100.
what have far this:
change_state = proc.new { |element| element == "open" ? element = "closed" : element = "open" } def janitor(array,n) in 1..n array.each { |element| if array.index(element) % == 0 element.change_state end } end end lockers = [*1..100] lockers = lockers.map{ |element| element = "closed" } result = janitor(lockers,100)
when trying execute receive error saying:
undefined method `change_state' "closed":string (nomethoderror)
anybody idea wrong here? kinda think i'm calling "change_state" proc incorrectly on current array element.
if know quiz, no spoilers please!
as have implemented change_state
, not method of class, , not 1 attached of individual elements of array, despite using same variable name element
. cannot call element.change_state
.
instead, variable pointing proc
object.
to call code in proc
object, use call
method, , syntax proc_obj.call( params )
- in case change_state.call( element )
if drop in change, error message change to:
nameerror: undefined local variable or method `change_state' main:object
that's because change_state
variable not in scope inside method, in order called. there lots of ways make available. 1 option pass in parameter, definition janitor becomes
def janitor(array,n,state_proc)
(use variable name state_proc
inside routine instead of change_state
- suggesting change name avoid confusing yourself)
you call this:
result = janitor(lockers,100,change_state)
although example not need structure, 1 way in ruby code can provide generic "outer" function - working through elements of array, - , have user of code provide small internal custom part of it. more common way achieve same result example use ruby block , yield
method, proc
s have uses, because can treat them data code - can pass them around, put them hashes or arrays decide 1 call etc.
there may other issues address in code, cause of error message in question.
Comments
Post a Comment