tags:

views:

37

answers:

3
def add app
  @has_app[app] = true
  @apps << app
end

In the code above, instead of using

@has_app[app] = true

to keep track of the presence of 'app', couldn't we also say:

@apps.include? (app)

and do away with @has_app?

I'm trying to understand why this separate variable is needed here at all (?).

+1  A: 

Methods with question-marks just check the state of variable instead of modifying it. Thus @apps.include?(app) would return either true or false depending on the array having the given object.

Eimantas
A: 

Yes, I agree with you. @has_app? is not a must. The only reason I can think of why the original coder used it is for performance's sake. Note that :

 @has_app is a Hash 
 @app is an Array.
pierr
+1  A: 

If this is the extent of the code, then yes, you could simply use the include? method. This is redundant data. It could be, though, that this hash of booleans has some different meaning that's not clear from these lines of code.

There would be a performance difference (for large lists), as a hash lookup is faster than an array lookup as the size increases. (You'd need to double check Ruby specifics, if this is important).

ndp