Skip to content

Instantly share code, notes, and snippets.

@samleb
Last active December 17, 2015 21:39
Show Gist options
  • Select an option

  • Save samleb/5676343 to your computer and use it in GitHub Desktop.

Select an option

Save samleb/5676343 to your computer and use it in GitHub Desktop.
def association_names_to_joins_argument(names)
joins = names.pop
joins = { names.pop => joins } until names.empty?
joins
end
association_names_to_joins_argument([:memberships])
# => :memberships
association_names_to_joins_argument([:memberships, :members])
# => { memberships: :members }
association_names_to_joins_argument([:users, :posts, :comments])
# => { users: { posts: :comments } }
@thbar

thbar commented May 30, 2013

Copy link
Copy Markdown

Not exactly the same behaviour for a single name, but a bit of inspiration maybe:

h = [:a, :b, :c, :d, :e, :f]

def hashize(a)
  a.size > 1 ? Hash[a.shift, hashize(a)] : a.first
end

puts hashize(h.dup).inspect

def hashize2(f, *a)
  a.empty? ? f : Hash[f, hashize2(*a)]
end

puts hashize2(*h.dup).inspect #

I prefer the first version and would make sure unit tests are in place ^_^

@samleb

samleb commented May 30, 2013

Copy link
Copy Markdown
Author

I like the way it reminds of Lisp's car/cdr recursive constructs, but as the method name will not be generic in this case (and is quite pretty huge), I'll rather stay with the "procedural" version, as both 3 versions have the side effect of modifying the original array.

@samleb

samleb commented May 30, 2013

Copy link
Copy Markdown
Author

BTW, even though it won't really apply without modifications in this case, it seems like Tail Call Optimization is still not turned on by default on 2.0.0:

RUBY_VERSION
# => "2.0.0"

RubyVM::InstructionSequence.compile_option
# => {:inline_const_cache=>true,
#     :peephole_optimization=>true,
#     :tailcall_optimization=>false,
#     :specialized_instruction=>true,
#     :operands_unification=>true,
#     :instructions_unification=>false,
#     :stack_caching=>false,
#     :trace_instruction=>true,
#     :debug_level=>0}

More on this on stackoverflow and this "turn by default" ticket.

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