Hello! I'm new to Ruby, but I spent some time with C. I would like to
know if the program I wrote was syntaxically correct for a Ruby program.
For example, I used a while loop to iterate through a string (with a
"i") to compare two strings... Should I have used Ruby's iterator?
Basically, the program is a *very* simple touch typing tutor. It reads
through a file to set the "lecture, for example : "jfjf fff ff jjf fj
jjjf fj" and then prints the line and asks the user for his answer. It
calculates number of errors (n_erreurs in french), precision in %, time
(okay too?).
I think your code looks way too much like C. IMO, if you end up using
C-like loop statement such as while or for it most likely means you are
not doing very good Ruby-like coding.
The way I would do your while loop would be something like this:
···
=====
#!/usr/bin/ruby
class String
def compare_sum_errors other
cnt = [self.length, other.length].min
(0..(cnt-1)).inject(0) do |errors, idx|
next errors + 1 if self[idx] != other[idx]
errors
end + (self.length - other.length).abs
end
end
I will finish my book and rewrite the program with a more ruby-like
syntax. The thing is I haven't read a lot about methods and classes
yet... guess I'll need some time to get used to Ruby too.
Meanwhile, I will study the code you gave me and figure out your "Ruby
Way".
Again, thank you very much and I hope to help you soon
I will finish my book and rewrite the program with a more ruby-like
syntax. The thing is I haven't read a lot about methods and classes
yet... guess I'll need some time to get used to Ruby too.
Methods and classes will allow you to avoid repeating the same code over and over. (For example in your original program you do a lot of print-get-sleep.)
Code that doesn't repeat itself is shorter, easier to test, and easier to understand -- which means that it's easier to fix; much easier.
Ruby programmers talk a lot about DRY: that just means "Don't Repeat Yourself". The golden target for any ruby programmer is never to code the same bit of code more than once, ever. (Of course it never works out quite that way, but it's a nice goal.)