adding string numbers together ruby - ruby

I have made this program which counts characters in your name.
puts 'What is your first name?'
forename = gets.chomp
puts 'what is your middle name?'
middlename = gets.chomp
puts 'what is your surname?'
surname = gets.chomp
puts 'Did you know there are ' + forename.length.to_s + middlename.length.to_s + surname.length.to_s + ' characters in your name?'
However this adds the numbers next to each other to equal 555 instead of 15.
I cant convert the lengths to integers as I won't be able to add the string of text before.

puts 'What is your first name?'
forename = gets.chomp
puts 'what is your middle name?'
middlename = gets.chomp
puts 'what is your surname?'
surname = gets.chomp
name_length = [forename,middlename,surname].map(&:length).inject(:+)
puts 'Did you know there are ' + name_length + ' characters in your name?'
OR simply without the #to_s. With #to_s you are converting numbers back to string and concatenating string.
puts 'What is your first name?'
forename = gets.chomp
puts 'what is your middle name?'
middlename = gets.chomp
puts 'what is your surname?'
surname = gets.chomp
puts 'Did you know there are ' + forename.length + middlename.length + surname.length + ' characters in your name?'

Related

How to add a loop in calculator program

I created a calculator in ruby. I am wondering how to put this in a loop so I don't have to run it constantly. I am new to programming so please understand I am I just trying to learn. I would appreciate any help provided.
puts "Hello, My name is Calvin The Calculator and I am a calculator that can do basic functions such as Adding, Subtracting, Multiplying and Dividing"
puts "Press a and enter to enable my services"
enable = gets.chomp
if enable == "a"
puts "Choose which operation you want to do. + for adding, - for subtraction, * for multiplication and / for division"
else
"Puts Im Waiting..."
end
which_operation = gets.chomp
if which_operation == "+"
puts "What is the first number you want to add"
adding_first_number = gets.chomp.to_i
puts "What is the second number you want to add to #{adding_first_number}"
adding_second_number = gets.chomp.to_i
puts "#{adding_first_number} + #{adding_second_number} is #{adding_first_number + adding_second_number}"
else
end
if which_operation == "-"
puts "What is the first number you want to subtract"
subtracting_first_number = gets.chomp.to_i
puts "What is the number you want to subtract from #{subtracting_first_number}"
subtracting_second_number = gets.chomp.to_i
puts "#{subtracting_first_number} - #{subtracting_second_number} is #{subtracting_first_number - subtracting_second_number}"
else
end
if which_operation == "*"
puts "What is the first number you want to multiple"
multiplying_first_number = gets.chomp.to_i
puts "What is the number you want to multiple #{multiplying_first_number} by"
multiplying_second_number = gets.chomp.to_i
puts "#{multiplying_first_number} * by #{multiplying_second_number} is #{multiplying_first_number * multiplying_second_number}"
else
end
if which_operation == "/"
puts "What is the first number to your divison question?"
dividing_first_number = gets.chomp.to_i
puts "What is the divisor?"
dividing_second_number = gets.chomp.to_i
puts "#{dividing_first_number} divided by #{dividing_second_number} is #{dividing_first_number / dividing_second_number}"
else
end
For example:
until (which_operation = gets.chomp).empty?
if which_operation == "+"
...
end
if which_operation == "-"
...
end
if which_operation == "*"
...
end
if which_operation == "/"
...
end
end
This loop will work until you press Enter without entering any text before it.
P.S.: Better use case operator instead of multiple if.
P.P.S.: All your code, after loop addition and without case operator, will be:
puts "Hello, My name is Calvin The Calculator and I am a calculator that can do basic functions such as Adding, Subtracting, Multiplying and Dividing"
puts "Press a and enter to enable my services"
until gets.chomp == "a"
puts "I'm Waiting..."
end
puts "Choose which operation you want to do. + for adding, - for subtraction, * for multiplication and / for division"
until (which_operation = gets.chomp).empty?
if which_operation == "+"
puts "What is the first number you want to add"
adding_first_number = gets.chomp.to_i
puts "What is the second number you want to add to #{adding_first_number}"
adding_second_number = gets.chomp.to_i
puts "#{adding_first_number} + #{adding_second_number} is #{adding_first_number + adding_second_number}"
elsif which_operation == "-"
puts "What is the first number you want to subtract"
subtracting_first_number = gets.chomp.to_i
puts "What is the number you want to subtract from #{subtracting_first_number}"
subtracting_second_number = gets.chomp.to_i
puts "#{subtracting_first_number} - #{subtracting_second_number} is #{subtracting_first_number - subtracting_second_number}"
elsif which_operation == "*"
puts "What is the first number you want to multiple"
multiplying_first_number = gets.chomp.to_i
puts "What is the number you want to multiple #{multiplying_first_number} by"
multiplying_second_number = gets.chomp.to_i
puts "#{multiplying_first_number} * by #{multiplying_second_number} is #{multiplying_first_number * multiplying_second_number}"
elsif which_operation == "/"
puts "What is the first number to your divison question?"
dividing_first_number = gets.chomp.to_i
puts "What is the divisor?"
dividing_second_number = gets.chomp.to_i
puts "#{dividing_first_number} divided by #{dividing_second_number} is #{dividing_first_number / dividing_second_number}"
end
puts "\nLet's try again: "
end

Ruby Hangman game, does not work when I enter the full word but only when I enter one letter

Run my code your ruby interpretor, to see my code. Afterwards, try to guess the full word. The program will tell you that your guess was correct but it doesn't end the game if you guess the entire word instead of each letter one by one.
I also want to add a Dictionary to my code to be able to play against the computer instead of with myself or a friend!
def clear_screen
return system('cls') if Gem.win_platform?
system('clear')
end
loop do
incorrect_guesses = 0
puts ''
puts 'Welcome to Hangman, Win or lose your life!'
puts ''
puts 'Choose Category: It can be anything you desire!'
player1_category = gets.chomp
puts ''
puts 'Player 1, Please enter your desired word'
secret_word = gets.chomp.downcase
clear_screen
correct_guess = ['-'] * secret_word.length
clear_screen
puts "The category is: #{player1_category}"
puts 'Player 2, Please enter your guess'
loop do
puts '_ ' * secret_word.length
player2_guess = gets.chomp.downcase
clear_screen
if secret_word.include? player2_guess
secret_word.each_char.with_index do |letter, i|
next unless letter == player2_guess
correct_guess[i] = letter
end
puts "The category is: #{player1_category}"
puts ''
print 'Guess the word: '
print correct_guess.join('')
puts ''
puts 'Correct. Keep trying!!'
puts ''
else
puts "The category is: #{player1_category}"
puts ''
print 'Guess the word: '
print correct_guess.join('')
puts ''
puts "The word doesn't contain that letter '#{player2_guess.upcase}'"
puts ''
incorrect_guesses += 1
end
puts "Incorrect Guesses: #{incorrect_guesses}"
puts ''
if incorrect_guesses == 6
puts ''
puts '|---+---+- '
puts '| |'
puts '| 0'
puts '| |\\'
puts '| /\\'
puts '-+----------'
puts "The Secret Word is '#{secret_word.capitalize!}'"
puts ''
break
end
next unless secret_word == correct_guess.join('')
puts ''
puts ' (#)'
puts ' ^\\|'
puts ' |/^'
puts '____|_____'
puts ''
puts 'You Win!'
puts ''
puts "You correctly guessed the word '#{secret_word.capitalize!}'"
break
end
end
I got to work with the following change to the next unless test:
if secret_word.include? player2_guess
secret_word.each_char.with_index do |letter, i|
next unless player2_guess.include? letter
correct_guess[i] = letter
end
You were comparing the entire entry to a single character. 't' != 'test'
As for a dictionary, the answer in this link should help
Your question is not super clear, but here are a few comments / answers:
Guessing the whole word: You could wrap your current if secret_word.include? player2_guess in another if that tests the length of the input. (This assumes all words are greater than 1 letter). The if statement should test if the user_input.length > 1. If so, evaluate whether the guess is the correct word, etc.
Adding a dictionary: Easiest was would be to hardcode an array of possible word values. If you want them to correspond to a category, you could make a hash like this {'category_1' => [word, word, word], 'category_2' => [word, word, word]}. Then you could pick a random value from the hash (category) and then a random value from the corresponding array.

Ruby: Is it possible to set an if statement == to 2 variables?

I am making a simple program that censors a users input based on the words chosen.
puts "Enter your Text: "
text = gets.chomp.downcase!
puts "Word to censor: "
censor1 = gets.chomp
censor1.downcase!
puts "Second word to censor: "
censor2 = gets.chomp
censor2.downcase!
words = text.split(" ")
words.each do |letter|
if letter == censor1
print "CENSORED "
else
print words + " "
end
end
So, is it possible to set: 'if letter == censor1 and censor 2' ?
You can check if object present in array with the help of Array#include?
if [censor1, censor2].include?(letter)
A bit simplified variant of your code:
puts 'Enter your Text: '
text = gets.chomp.downcase
puts 'Word to censor: '
censor1 = gets.chomp.downcase
puts 'Second word to censor: '
censor2 = gets.chomp.downcase
text.split(' ').each do |word|
if [censor1, censor2].include?(word)
print 'CENSORED '
else
print word + ' '
end
end
And much easier and better solution with String#gsub which replaces all occurrences of censored words in text:
puts 'Enter your Text: '
text = gets.chomp.downcase
puts 'Word to censor: '
censor1 = gets.chomp.downcase
puts 'Second word to censor: '
censor2 = gets.chomp.downcase
[censor1, censor2].each { |c| text.gsub!(c, 'CENSORED') }
puts text
If you are asking if either (downcased) censorX contains the character letter:
censor1+censor2.include?(letter)
If you are asking if both censorX's contain the character letter:
censor1.include?(letter) && censor1.include?(letter)
If you are asking if all censorX strings equal the string letter, then:
if [censor1, censor2,...].uniq == [letter]
...
end

Redacted Iterator in Ruby

I am going through a Ruby course on Codecademy.com. The problem is listed under Iterators and Loops. Here are the instructions:
Let's start simple: write an .each loop that goes through words and just prints out each word it finds.
Here is what I have which does not seem to pass the test, so I just want to know if it is correct or not.
puts "need input please"
text = gets.chomp
words = text.split(" ")
words.each do |x|
puts "#{x}"
end
puts "need another input"
redact = gets.chomp
Somewhat oddly, this is what passed the course example
puts "need input please"
text = gets.chomp
words = text.split(" ")
redact = gets.chomp
Which is obcviously not right since it does not make use of the .each loop.
words.each do |x|
puts "#{x}"
end
x is your block variable, and doesn't need to be interpolated.
Try
words.each do |x|
puts x
end
hello im doing the same course on codecademy and wrote this even though it lets me pass im unsure if its correct if this helps
puts "Enter paragraph here: "
text=gets.chomp
puts "Word to redact"
redact = gets.chomp
words = text.split {" "}
words.each do |words|
if words == redact
print "REDACTED "
else
print words + " "
end
end

Programming a basic calculator in Ruby

This is my first foray into computer programming. I have chosen to learn Ruby, and I am enjoying it quite a bit. However, I am a little confused as to why the answer will not output properly in this bit of code.
def addition_function
puts "Which numbers would you like to add?"
#n1 = gets.chomp
#n2 = gets.chomp
#n1 + #n2 == #answer
puts "The sum is... #{#answer}"
end
def subtraction_function
puts "Which numbers would you like to subtract?"
#n1 = gets.chomp.to_i
#n2 = gets.chomp.to_i
#n1 - #n2 == #answer
puts "The answer is... #{#answer}"
end
def multiplication_function
puts "Which numbers would you like to multiply?"
#n1 = gets.chomp
#n2 = gets.chomp
#n1 * #n2 == #answer
puts "The answer is... #{#answer}"
end
puts "Would you like to [add], [multiply], or [subtract]?"
response = gets.chomp
if response == "add" then
addition_function
end
if response == "subtract" then
subtraction_function
end
if response == "multiply" then
multiplication_function
end
I know this is probably horrible code... but could someone help steer me in the right direction?
Consider this code:
def get_int_values
[gets, gets].map{ |s| s.chomp.to_i }
end
puts "Would you like to [add], [multiply], or [subtract]?"
response = gets.chomp
case response.downcase
when 'add'
puts "Which numbers would you like to add?"
operator = :+
when 'subtract'
puts "Which numbers would you like to subtract?"
operator = :-
when 'multiply'
puts "Which numbers would you like to multiply?"
operator = :*
end
answer = get_int_values.inject(operator)
puts "The answer is... #{ answer }"
The idea is to follow the "DRY" principle: "DRY" means "Don't Repeat Yourself", which the vast majority of the time, is a really good thing.
To help avoid typing mistakes I'd recommend doing something like:
puts "Would you like to [a]dd, [m]ultiply, or [s]ubtract?"
response = gets.chomp
case response[0].downcase
then change the when clauses to match the first letter of the desired operation.
Which will work unless response is empty. You can figure out how to handle that.
another way to obtain answer, once operator is determined, is answer = gets.to_i.send(operator, gets.to_i)
That's true, but here's why I refactored the code the way I did: If, for some reason, there was a need to operate on more than two values, only one thing has to be changed:
[gets, gets].map{ |s| s.chomp.to_i }
could become:
[gets, gets, gets].map{ |s| s.chomp.to_i }
Or, better, could be transformed to something like:
def get_int_values(n)
n.times.map { gets.chomp.to_i }
end
Nothing else will have to change except to find out how many values are needed.
Now, to do it all right would require different text to alert the user that multiple values are expected, but that's easily done by letting letting the user say how many they want to enter, and then prompting for each gets:
def get_int_values(n)
n.times.map.with_index { |n|
print "Enter value ##{ 1 + n }: "
gets.chomp.to_i
}
end
puts "Would you like to [add], [multiply], or [subtract]?"
response = gets.chomp
puts "How many values?"
num_of_values = gets.to_i
case response.downcase
when 'add'
puts "Which numbers would you like to add?"
operator = :+
when 'subtract'
puts "Which numbers would you like to subtract?"
operator = :-
when 'multiply'
puts "Which numbers would you like to multiply?"
operator = :*
end
answer = get_int_values(num_of_values).inject(operator)
puts "The answer is... #{ answer }"
inject can scale up easily because it doesn't presuppose knowledge about the number of values being operated on.
I think with_index in n.times.map.with_index is an artifact you forgot to delete.
It was deliberate but I like this better:
def get_int_values(n)
1.upto(n).map { |n|
print "Enter value ##{ n }: "
gets.chomp.to_i
}
end
Your assignments are on the wrong side of the statement. You should have answer = n1 * n2,
which is not the same as answer == n1 * n2 (this is a check for equality, using ==). The expression always goes on the right, and the variable the result is assigned to goes on the left -- this is pretty much universal, but not necessarily intuitive coming from algebra.
Also: using an # prior to a variable name differentiates it as an instance variable, or member, of a class. From what you've shown here you don't need to include those, just normally scoped variables are required for this use.
Check out this question for more on that part.
The "#" sigil is used to indicate a class instance variable, you have no class so don't use it.
#n1 + #n2 == #answer
Is a boolean expression evaluating whether #n1 + #n2 is equal to #answer.
It will evaluate to true or false.... but you don't make use of the answer.
What you want is ...
answer = n1 + n2
I strongly recommend you always run Ruby with the -w option. It will save you much much heartache.
Please indent your "end"'s to match your "def" (or "if").
You repeat n1 = gets.chomp.to_i all over the place, do it once and pass the answers as a parameter...
response = gets.chomp
n1 = gets.chomp.to_i
n2 = gets.chomp.to_i
if response == "add" then
addition_function( n1, n2)
elsif...
A few suggestions not mentioned by others:
Shorten your method (not "function") names and use verbs (e.g., add instead of addition_method).
As well as using local variables rather than instance variables (mentioned by others), eliminate them where you can. For example, you could simplify
.
def add
puts "Which numbers would you like to add?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 + n2
puts "The sum is... #{answer}"
end
to
def add
puts "Which numbers would you like to add?"
puts "The sum is... #{gets.to_i + gets.to_i}"
end
Notice I've used the Ruby convention of indenting two spaces.
You don't need chomp here (though it does no harm), because "123followed by \n or any other non-digits".to_i => 123.
A case statement would work well at the end (and let's loop until the user chooses to quit):
.
loop do
puts "Would you like to [add], [multiply], [subtract] or [quit]?"
case gets.chomp
when "add"
add
when "subtract"
subtract
when "multiply"
multiply
when "quit"
break
end
or just
def quit() break end
loop do
puts "Would you like to [add], [multiply], [subtract] or [quit]?"
send(gets.chomp)
end
Here we do need chomp. You could replace loop do with while true do or use other equivalent constructs.
class Calculator
def Calc
puts"==well come to mobiloitte calculator=="
puts "enter the first operand:"
#op1 = gets.chomp
return if #op1=="q"
#o1=#op1.to_i
puts "entre the second operand:"
#op2 = gets.chomp
return if #op2=="q"
#o2=#op2.to_i
strong text puts "enter any one operator of your choice (add,sub,mul,div,mod)"
operator = gets.chomp
case operator
when 'add' then #s=#o1+#o2 ; puts "\n ##o1 + ##o2 =##s"
when 'sub' then #t=#o1-#o2 ; puts "\n ##o1 - ##o2 =##t"
when 'mul' then #l=#o1*#o2 ; puts "\n ##o1 * ##o2 =##l"
when 'div' then #r=#o1/#o2 ; puts "\n ##o1 \ ##o2 =##r"
when 'md' then #d=#o1%#o2 ; puts "\n ##o1 % ##o2 =##d"
else
puts"invalide input"
end
end
end
obj= Calculator.new
$f=obj.Calc
You are using #n1 + #n2 == #answer to try and set the answer. What you want to do is #answer = #n1 + #n2.
= is assignment, == is a comparison operator.
Also, you will need to #n1 = gets.chomp.to_i. This will convert your input to an integer from a string. Do that with #n2 as well.
You also do not need to use the # before each of your variables. That should only be used when you are dealing with classes, which you do not appear to be doing.
print "enter number 1 : "
n1 = gets.chomp.to_f
print "enter number 2 : "
n2 = gets.chomp.to_f
print "enter operator: "
op = gets.chomp
if op == '+'
puts "#{n1} + #{n2} = #{n1 + n2}"
elsif op == '-'
puts "#{n1} - #{n2} = #{n1 - n2}"
elsif op == '*'
puts "#{n1} * #{n2} = #{n1 * n2}"
elsif op == '/'
puts "#{n1} / #{n2} = #{n1 / n2}"
end
puts "Would you like to
0 ---- [exit],
1 ---- [add],
2 ---- [subtract],
3 ---- [multiply],
4 ---- [divide]"
response = gets.chomp
case response.downcase
when '1'
def addition_function
puts "Which numbers would you like to add?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 + n2
puts "The sum is... #{n1} + #{n2} = #{answer}"
end
addition_function()
#Subtract
when '2'
def subtraction_function
puts "Which numbers would you like to subtact?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 - n2
puts "The subtraction is... #{n1} - #{n2} = #{answer}"
end
subtraction_function()
#Multiply
when '3'
def multiplication_function
puts "Which numbers would you like to multiply?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 * n2
puts "The multiplication is... #{n1} * #{n2} = #{answer}"
end
multiplication_function()
#Division
when '4'
def division_function
puts "Which numbers would you like to divide?"
n1 = gets.to_i
n2 = gets.to_i
answer = n1 / n2
puts "The division is... #{n1} / #{n2} = #{answer}"
end
division_function()
else '0'
puts "Exit! Thank You for using us!"
end
#ruby script to do the calculator
puts " enter the number1"
in1=gets.to_i
puts " enter the number2"
in2=gets.to_i
puts "enter the operator"
op=gets.chomp
case op
when '+'
plus=in1+in2
puts "#{in1+in2}"
#puts "#{plus}"
when '-'
min=in1-in2
puts "#{min}"
when '*'
mul= in1*in2
puts "#{mul}"
when '/'
div=in1/in2
puts "#{div}"
else
puts "invalid operator"
end
begin
puts 'First number:'
a = $stdin.gets.chomp.to_i
puts 'Second number:'
b = $stdin.gets.chomp.to_i
operation = nil
unless ['+', '-', '*', '/', '**'].include?(operation)
puts 'Choose operation: (+ - * /):'
operation = $stdin.gets.chomp
end
result = nil
success = false
case operation
when '+'
result = (a + b).to_s
when '-'
result = (a - b).to_s
when '*'
result = (a * b).to_s
when '/'
result = (a / b).to_s
when '**'
result = (a**b).to_s
else
puts 'There is not such kind of operation'
end
success = true
puts "Результат: #{result}"
rescue ZeroDivisionError => e
puts "You tried to devide number by zero! Error: #{e.message}"
end
if success
puts "\nSuccess!"
else
puts "\nSomething goes wrong :("
end
puts ("plz enter a number :")
num1 = gets.chomp.to_f
puts ("plz enter a another number")
num2 = gets.chomp.to_f
puts ("plz enter the operation + , - , x , / ")
opp = gets.chomp
if opp == "+"
puts (num1 + num2)
elsif opp == "-"
puts (num1 - num2)
elsif opp == "x"
puts (num1 * num2)
elsif opp == "/"
puts (num1 / num2)
else puts ("try again :|")
end

Resources