Skip to content

Instantly share code, notes, and snippets.

@jc00ke
Created September 18, 2018 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jc00ke/968f32d021fe4da07401acec36b93585 to your computer and use it in GitHub Desktop.
Save jc00ke/968f32d021fe4da07401acec36b93585 to your computer and use it in GitHub Desktop.
def bar
:bar
end
def foo(a, b=bar)
puts [a, b].inspect
end
foo("hi")
# => ["hi", :bar]
foo("hi", "this is my bar")
# => ["hi", "this is my bar"]
def foo(a, b=bar()) # do the parens help?
puts [a, b].inspect
end
foo("hi")
# => ["hi", :bar]
@jc00ke
Copy link
Author

jc00ke commented Sep 18, 2018

def foo(a, b=bar)
  puts [a, b].inspect
end

foo(1, 2)
# => [1, 2]

foo(1)
# foo.rb:1:in `foo': undefined local variable or method `bar' for main:Object (NameError)

def foo(a, b=bar())
  puts [a, b].inspect
end

foo(1, 2)
# => [1, 2]

foo(1)
# foo.rb:1:in `foo': undefined method `bar' for main:Object (NoMethodError)

@jc00ke
Copy link
Author

jc00ke commented Sep 18, 2018

What I'm really asking is:

Which is "better" (not necessarily more idiomatic)

def bar
  :bar
end

def foo(a, b=nil)
  b ||= bar
  # ...
end

def foo(a, b=nil)
  if b.nil?
    b = bar
  end
  # ...
end

def foo(a, b=bar) # or kwargs, doesn't really matter
  # no checking necessary
  # ...
end

def foo(a, b=bar()) # or kwargs, doesn't really matter
  # no checking necessary
  # ...
end

@jc00ke
Copy link
Author

jc00ke commented Sep 18, 2018

Turns out, the 2nd arg is never passed in code or tests anyway, so I'm going with

def foo(a)
  b = bar
  # ...
end

bar is actually a ActiveRecord::FinderMethods.find_by! and we can't continue of the model doesn't exist anyway.

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