Since I have been trying to learn rails, I have also been learning to use ruby. I don’t currently have any questions, however I want to make my presence clear that I have not “given up” and so I am just posting some Ruby tricks to make clearer code that I found useful.
Instead of lots of if else comparison statements (if 200 < num && num < 300) it is possible to use ranges as such:
puts case num
when 200..300: "two hundreds"
when 300..400: "three hundreds"
end
Also ruby objects have a tap method that can replace this:
def create_some_object(params)
object = SomeClass.new
object.field1 = 'some value'
object.field2 = 'some other value'
object.some_method!
object
end
with this:
def create_some_object(params)
SomeClass.new.tap do |o|
o.field1 = 'some value'
o.field2 = 'some other value'
o.some_method!
end
end
Neat, huh!
Hope you have learned some better ruby practices.