Skip to content

Instantly share code, notes, and snippets.

@tlands
Created June 24, 2013 17:10
Show Gist options
  • Save tlands/5851735 to your computer and use it in GitHub Desktop.
Save tlands/5851735 to your computer and use it in GitHub Desktop.
Fibonacci numbers : True or False
def is_fibonacci?(i)
a = 0
b = 1
while true
c = a + b
return true if c == i # the more I look at this... it's a little iffy and should be redone.
return false if c > i
a,b = b, c # eval right assign left...'b' (r) is assigned to 'a'(l), 'c'(r) is assigned to 'b'(l)
end
end
@jfarmer
Copy link

jfarmer commented Jun 24, 2013

Here are things that should smell funny to you:

  1. A while(true) loop in a situation where you know beforehand when the loop will terminate, e.g., you might use a while(true) loop while reading and parsing user input because you don't know beforehand when a user will type "exit"
  2. Multiple references to return in the middle of a method
  3. Calls to return in the middle of a loop
  4. Inconsistent use of multiple assignment, e.g., you use it in the loop but not outside the loop
  5. Superfluous variables, e.g., c
  6. Unhelpful, single-letter variable names

Here's a suggested refactoring:

def is_fibonacci?(num)
  last, cur = 0, 1

  while cur <= num
    last, cur = cur, last + cur
  end

  num == last
end

or equivalently (some folks might argue this reads better but YMMV — they're equivalent):

def is_fibonacci?(num)
  last, cur = 0, 1

  until cur > num
    last, cur = cur, last + cur
  end

  num == last
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment