small medium large xlarge

Pp6-2-400x400_pragsmall
13 Feb 2015, 14:54
xavier nayrac (1 post)

Hello, Given my experience, I’m not sure that your code:

def neighbors
  list = []
  list << north if north
  list << south if south
  list << east if east
  list << west if west
  list
end

is easier to read for a Ruby newbie than this one:

def neighbors
  [north, south, east, west].compact
end

What do you think?

Generic-user-small
14 Feb 2015, 05:22
Jamis Buck (30 posts)

Hello Xavier! Thank you for your comment. You’re absolutely right that the second way (using Array#compact) is better Ruby code. I originally had it implemented that way, but I worried that the Array#compact idiom would require more explanation for non-Rubyists. The first version is more verbose, but I think it explains the intention better, and is more easily portable to other languages.

Ultimately, this means that there will be more idiomatic ways to implement many of these methods in Ruby, but it’s a trade-off.

I’ll consider this some more, but ultimately I don’t want non-Rubyists to be discouraged from reading this book—the algorithms are really at the core of it.

Thanks again! I really appreciate your feedback on this issue. It’s been a tricky one for me to find a balance here.

Generic-user-small
16 Feb 2015, 08:56
Wari Wahab (6 posts)

I’m reading ruby code and just port it to Go, see: https://github.com/wari/mazes/tree/ch-2

So yes, I would understand better with the top version, as there is no “compact” in Go unless I create it myself. That particular code is in https://github.com/wari/mazes/blob/ch-2/cell.go#L58

Generic-user-small
16 Feb 2015, 21:24
Jamis Buck (30 posts)

Thanks for the feedback, Wari! That’s very helpful to hear that you prefer the first version. Also, I’m excited to hear that you’re porting the Ruby implementation from the Book, to Go! I look forward to seeing how it comes together for you.

You must be logged in to comment