Ruby TTT

On Monday I started my Ruby Tic Tac Toe. This is the 4th tic tac toe, I have done. I have previously done it in Lua, Java, CSharp and now in Ruby.

As repetitive as it is, its nice seeing the improvements with everyone I do. Its only been a couple months since my last tic tac toe which was in CSharp, and I already feel like I made a lot of mistakes with it which I hope to rectify in the Ruby one I am doing now.

One example is, now I am really conscious of how many lines my classes are. In my previous tic tac toes, there are a lot of 100–150 line classes which is just unacceptable. Most classes should only have one responsibility, and if the class has over 100 lines the chances are that there is more than one responsibility; which was true in my old tic tac toes. Ruby also makes writing less code very easy, a couple examples:

Before:

array = [1, 2, 3]
array.each do |number|
puts number
end

After:

array = [1, 2, 3]
array.all? {|number| puts number}

Before:

@array = [1, 2, 3]
def contains_one?(array)
array.each do |number|
return true if number == 1
end
return false
end

After:

@array = [1, 2, 3]
def contains_one?(array)
array.any? {|number| number == 1}
end

Before:

@users = [{name: "Will", age: 17}, {name: "Bob", age: 17}]
def find_users_by_name(name)
requested_users = []
@users.each do |user|
requested_users << user if user.name == name
end
return requested_users
end

After:

@users = [{name: "Will", age: 17}, {name: "Bob", age: 17}]
def find_user_by_name(name)
@users.select {|user| user.name == name}
end