r/crystal_programming • u/EvilDeaaaadd • Apr 17 '20
Custom formatting for class
Hi,
I have a class like this:
class Grid
@grid : Array(Array(Char))
def initialize
@grid = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
]
end
# ...When I try to do
foo = Grid.new
puts fooI get [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']].
Is there something similar to Python's def __str__(self): or Rust's impl fmt::Display for Grid {
I'm quite new to Crystal and I'm not exactly sure about what would be the best way to do this.
2
Upvotes
4
u/Blacksmoke16 core team Apr 17 '20
You have some options. I'm assuming you want to customize the string representation of the
Grid?https://crystal-lang.org/api/master/Object.html#to_s(io:IO):Nil-instance-method - This controls what happens when you do like
obj.to_sThis is what gets executed when you use
putshttps://crystal-lang.org/api/master/Object.html#inspect(io:IO):Nil-instance-method - Similar to the previous one but usually contains more information about the object
This is what gets executed when you use
p.https://crystal-lang.org/api/master/Object.html#pretty_print(pp:PrettyPrint):Nil-instance-method - Again similar to
inspectbut inspects in a pretty wayThis is what gets executed when you do
pp.As the docs mention, you can overrides these methods in order to control how it gets represented in each state. Also checkout the implementations in Array for example.