2
\$\begingroup\$

For a given file name path, I need to get the folder one level before it. This can be accomplished in ruby with the following code:

File.dirname(File.dirname("/a/b/c.txt"))
 => "/a" 

Independently from this exact case, how can I DRY two method calls in sequence?

\$\endgroup\$
5
\$\begingroup\$

You should consider any DRYing efforts in terms of its effects on code clarity. I don't think that trying to reduce foo(foo(bar)) is worth the reduced clarity. Now, if we're trying to reduce foo(foo(foo(foo(foo(bar))))), that's something else. One way you can do that is using reduce:

5.times.reduce(1 << 64) { |x,| Math.sqrt(x) }
=> 4.0

5.times.reduce('/a/b/c/d/e/f.txt') { |x,| File.dirname(x) }
=> "/a"
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.