patternrubyMinor
Guess a number, any number, between 1 and 10
Viewed 0 times
numberanybetweenandguess
Problem
I am learning Ruby and would like to know how I am doing as far as writing the actual code.
Please keep in mind that this is my first Ruby script program, but I am trying to learn ruby in a very short period of time.
I would like to know about nitpicks in the language that every Ruby writer should now, nuances in syntax, and other Ruby specific ... things.
Please keep in mind that this is my first Ruby script program, but I am trying to learn ruby in a very short period of time.
I would like to know about nitpicks in the language that every Ruby writer should now, nuances in syntax, and other Ruby specific ... things.
$randomNumber = rand(10) + 1
def guessRandomNumber
puts "Guess a number between 1 and 10"
guess = gets
if Integer(guess) == $randomNumber
puts "Right on, good guess"
elsif Integer(guess) $randomNumber
puts "too high"
puts "please, guess again"
guessRandomNumber
else
puts "is that even a number? please, guess again"
guessRandomNumber
end
end
guessRandomNumber
puts "bye"
getsSolution
Global variables
Don't use global variables(like
Style
Huge percentage of the Ruby community follow the style guide and this
is the most popular one Ruby style guide.
Style issues:
About the implementation
IMO will be more readable like this:
You see there is no need to expose the variable in the global scope.
Don't use global variables(like
$bar). It is always bad practice because you can mutate the global variable from anywhere. The alternative is:RANDOM_NUMBER = rand(1..10), notice that you can pass range as an argument of rand. rand(10) + 1 can return 11 so it isn't correct.Style
Huge percentage of the Ruby community follow the style guide and this
is the most popular one Ruby style guide.
Style issues:
- Use snake case for the names of methods and variables.
- Use double quotes only if you use interpolation or special symbols like
\n.
About the implementation
IMO will be more readable like this:
def guess_random_number
puts 'Guess a number between 1 and 10'
random_number = rand(1..10)
while random_number != (guess_number = gets.to_i)
if guess_number < random_number
puts "too low \nplease, guess again"
else
puts "too high \nplease, guess again"
end
end
puts "Right on, good guess \nbye"
end
guess_random_numberYou see there is no need to expose the variable in the global scope.
Code Snippets
def guess_random_number
puts 'Guess a number between 1 and 10'
random_number = rand(1..10)
while random_number != (guess_number = gets.to_i)
if guess_number < random_number
puts "too low \nplease, guess again"
else
puts "too high \nplease, guess again"
end
end
puts "Right on, good guess \nbye"
end
guess_random_numberContext
StackExchange Code Review Q#128874, answer score: 7
Revisions (0)
No revisions yet.