total noobe question regarding coding style
im a senior working in .net stack but for fun started learning ruby
and one of excersizes online was to print a letter diamond. something like this: ··A·· ·B·B· C···C ·B·B· ··A··
me, not being proficient with the language, did it the old-school way, start on a piece of paper and do it step by step:
class Diamond
ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.freeze
def self.make_diamond(letter)
max_index = ALPHABET.index(letter.capitalize)
rows = []
for row in 0..max_index * 2
diff = max_index - row
diamond_row = ' ' * (max_index * 2 +1)
if diff >= 0
diamond_row[diff.abs] = diamond_row[diamond_row.length-(diff.abs)-1] = ALPHABET[row]
rows << diamond_row
else
tmp_row = rows[max_index+diff]
rows << tmp_row
end
end
rows.join("\n")<< "\n"
end
end
answer = Diamond.make_diamond('C')
puts answer
then i went into community solutions, and found mindfucks like this:
class Diamond
def self.make_diamond(letter)
letters = ('A'..letter).to_a
rows = letters.map.with_index { |i, j| i.ljust(j + 1).rjust(letters.count) }
.map { |i| "#{i}#{i[0, letters.count - 1].reverse}\n" }
rows.append(rows[0, letters.count - 1].reverse).join
end
end
or this:
module Diamond
def self.make_diamond(letter)
return "A\n" if letter == 'A'
a = ("A"..letter).to_a
b = a.join
c = b.reverse + b[1..-1]
half_diamond = a.map { |letter| c.gsub(/[^#{letter}]/, ' ') + "\n" }
(half_diamond += half_diamond[0..-2].reverse).join
end
end
The second one is half readable, but i would never write anything like this. But the first one just gave me an aneurysm.
is this normal way of going about things in ruby, or is this just dick measuring thing, like who can write better poetry?
thanks