HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Fractal generator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fractalgeneratorstackoverflow

Problem

Refer to the help message and title of this post for what the code does.

I'm looking for tips on:

  • Efficiency: While the find-and-replace approach I have works perfectly fine and does so in a relatively quick manner, it feels far slower than it could be.



  • Idiomaticness: As always, I like writing code that abuses every feature it can.



-
Code readability: It's pretty freaking complicated. Even I barely understand what the heck is going on here:

self.chunk(rows).map { |row| row.shift.zip(*row) }.map { |col| col.chunk(cols) }.flatten(1)


Note that I'm not asking for an explanation. I wrote the code; I understand how it works. I'm asking for tips to improve readability.

  • Help message: Everything about this. I've never been particularly good at writing documentation for other people to use.



```
require 'pathname'

if ARGV == ['-h'] || ARGV == ['/?']
file = Pathname.new(__FILE__).relative_path_from(Pathname.new(Dir.getwd))
puts
| | ruby #{file} -g
|
| Command-line flags:
| -------------------
|
| -h OR /?: Display this help message.
| -g: Retrieve the data from standard input, rather than the command line.
END
exit
end

pattern = []
rules = {}
count = Integer(ARGV.shift)

if ARGV.length == 1 && ARGV[0] == '-g'
pattern ').map { |s| s.split(',').map(&:chars) }
rules[from] = to
end
else
pattern = IO.readlines(ARGV[0]).map(&:chomp).map(&:chars)
rules = Hash[
IO.readlines(ARGV[1]).map(&:chomp).reject { |line| line.empty? }.map do |line|
line.split('>').map { |half| half.split(',').map(&:chars) }
end
]
end

class Array
def dimensions
width = self[0].size
jagged = self.any? { |row| row.size != width }
[self.size, jagged ? nil : width]
end

def chunk(chunk_size)
self.each_with_index.with_object(Array.new(size / chunk_size) { [] }) do |(elt, ind), result|
result[ind / chunk_size] << elt
end
end

def to_cells(cell_dims)
rows, cols = cell_dim

Solution

I think I found a bug:

pattern << $_.chars until gets == ''


The problem here is that gets cannot return an empty string, so this probably does not behave as you think it should.

Look at this REPL session:

irb(main):003:0> gets

=> "\n"


I think that just adding .chomp after gets should fix this.

Code Snippets

pattern << $_.chars until gets == ''
irb(main):003:0> gets

=> "\n"

Context

StackExchange Code Review Q#99192, answer score: 2

Revisions (0)

No revisions yet.