I worte an simple programm to replace text within (( )) with the user input:
If i have for example this this text:
i hab an terrible ((userinput1)) last ((userinput2)) in a horrible ((userinput3))
I tried first to replace the (( with #{ and the )) with }
str1 = gets.chomp
str2 = str1.clone
a = 0
begin
s = str2.index('((', a)
str2[s..s+1] = '#{'
a = a + s + 1
end until str2.length < a
b = 0
begin
s = str2.index('))', b)
str2[s..s+1] = '}'
b = b + s + 1
end until str2.length < b
userinput1 = gets.chomp
userinput2 = gets.chomp
userinput3 = gets.chomp
puts str2
But somehow ruby dont validates the userinputs, instead i get:
i hab an terrible #{userinput1} last #{userinput2} in a horrible #{userinput}
I think the problem is that in my code i wrote:
str2[s..s+1] = '#{'
instead of
str2[s..s+1] = "#{"
because so all my remaining code is an object until it is closed with }. SO what can i do ? I hope you understood my issue?
str1 = gets.chomp
word = str1.scan(/\(\(\w+\)\)/)
word.each do |word|
str1.gsub(word, "what the fuck")
end
puts str1
Nice try. But there's a simpler way. Much simpler :) Basically, you just have to collect user inputs. There are methods for replacing string parts already.
userinput1 = gets.chomp
userinput2 = gets.chomp
userinput3 = gets.chomp
template = "i had a terrible ((userinput1)) last ((userinput2)) in a horrible ((userinput3)"
result = template.gsub('((userinput1))', userinput1).
gsub('((userinput2))', userinput2).
gsub('((userinput3))', userinput3)
# ^^ replacing happens here
puts result
Related
I'm working on a program that gives the user two random numbers ranging from 0 to 10 for the user to divide, multiply, add, or subtract.
After every question, the user has the opportunity to stop the program by typing no.
I am using a while loop for this, but I can't get the loop to terminate when the user inputs no. How can I get the program to respond correctly to the user input?
def math_num
nums = [num_1 = rand(1..10), num_2 = rand(1..10), operator = ["+", "-", "/", "*"].sample]
problem = "What is #{num_1} #{operator} #{num_2}?"
puts problem
$input = gets.to_i
$answer = num_1.send(operator, num_2)
puts $input == $answer ? "You answered #{$input}, and the answer is #{$answer}! You are correct!" : "The answer is #{$answer}, not #{$input}! You are incorrect!"
def try_again
puts "Would you like to do another question?"
another = gets.chomp.to_s
while another != "no"
math_num
end
end
try_again
end
math_num
Well, the way you are doing it you are getting an infinite loop since the value of the another variable is not being updated inside the while loop.
Try this instead:
def math_num
while true
nums = [num_1 = rand(1..10), num_2 = rand(1..10), operator = ["+", "-", "/","*"].sample]
problem = "What is #{num_1} #{operator} #{num_2}?"
puts problem
$input = gets.to_i
$answer = num_1.send(operator, num_2)
puts $input == $answer ? "You answered #{$input}, and the answer is #{$answer}! You are correct!" : "The answer is #{$answer}, not #{$input}! You are incorrect!"
puts "Would you like to do another question?"
another = gets.chomp.to_s
if another == "no"
break
end
end
end
math_num
i have this code :
#require_relative '../lib/hackex/net/typhoeus'
require_relative '../lib/hackex'
require 'rubygems'
require 'faker'
print "how many farms do you want : "
choice = gets.chomp
choice.to_i
check = choice.is_a?(Integer)
puts check
if choice > 250
puts "Error! you cannot make more than 250 farms at once"
elsif choice < 250
puts "Error! you have to make at least one farm..."
elsif choice.is_a?(Integer) == false
puts "Error, something went wrong !"
else
puts "making #{choice} acounts ! ! !"
cnt = 1
while choice>cnt
gen = Faker::Name.first_name + Faker::Name.last_name
path=("created1.txt")
email = gen+'#gmail.com'
password = Faker::Internet.password(8)
username = gen.to_s+'/>'
puts HackEx::Request.Do(http,HackEx::Request.CreateUser(username, email, password, facebook_id = nil))
cnt +=1
open(path, 'a') { |f|
f << "#{email};"
f << "#{password}"
f << "\n"
}
puts "Account created!"
puts "#{choice - cnt} accounts remaining!"
end
end
i am trying to determing if the choice is an integer... i did the .to_i on choice, but it returns false, meaning its not an integer, its a string, why isnt it switching ?
ps : i do not get any errors, and the rest of the code works fine, except for the if part
choice.to_i returns an integer, but does not change choice. If you want choice to be changed to the integral value of the old choice, you need to reassign it explicitly:
choice = choice.to_i
Quoting the doc of String::to_i, emphasis is mine
to_i(base=10) → integer
Returns the result of interpreting leading characters in str as an
integer base base (between 2 and 36).
So you have to assign the return to something, or itself:
choice = choice.to_i
While trying to make a calculator in Ruby, using TextWrangler's #! function (Compiled in Terminal) I encountered an error. When I add 2+2 the answer it returns is 2.0. I tried other functions, for example calculating a specific percentage of a certain number, no matter what I tried doing the answer was always 0.0. I checked the syntax, using the #! function, and there were no errors. I know I made it unnecessarily wrong, but it is easier to read it this way for me.
loop do
print
equation = gets.chomp
if equation.include?"^"
exponent_e = equation.split("^")
result_e = equation[0].to_f ** equation[1].to_f
puts "#{equation} = #{result_e}"
elsif equation.include?"%"
percent_e = equation.split("%")
number = equation[0].to_f / 100
result_p = number * equation[1].to_f
puts "#{equation} = #{result_p}"
elsif equation.include?"/"
equation.split("/")
result_d = equation[0].to_f / equation[1].to_f
puts "#{equation} = #{result_d}"
elsif equation.include?"*"
equation.split("*")
result_m = equation[0].to_f * equation[1].to_f
puts "#{equation} = #{result_m}"
elsif equation.include?"+"
equation.split("+")
result_a = equation[0].to_f + equation[1].to_f
puts "#{equation} = #{result_a}"
elsif equation.include?"-"
equation.split("-")
result_s = eqaution[0].to_f - equation[1].to_f
puts "#{equation} = #{result_s}"
end
end
You're not storing the split in a variable. You need to do something like this:
elsif equation.include?"+"
res = equation.split("+")
result_a = res[0].to_f + res[1].to_f
First post, excuse if I break any etiquette. I am beginning, so this might be simple.
Trying to code in ruby, a calculator, where user inputs arithmetic sentence (only binary, PEMDAS/BIDMAS will do later) and the answer comes out.
Here is my code, by only works for single digit numbers.
class Calculator
def initializer (a,b)
#a = a,
#b = b
end
def add(a, b)
a+b
end
def subtract(a, b)
a-b
end
def multiply(a,b)
a*b
end
def divide (a,b)
a/b
end
def powers (a,b)
a**b
end
end
puts "Enter an expression to be evaluated"
a = gets.chomp.gsub(/\s+/, "")
puts case a[1]
when "+"
"#{a[0]} + #{a[2]} = #{Calculator.new.add(a[0].to_f,a[2].to_f)}"
when "-"
"#{a[0]} - #{a[2]} = #{Calculator.new.subtract(a[0].to_f,a[2].to_f)}"
when "*" || "x" || "X"
"#{a[0]} x #{a[2]} = #{Calculator.new.multiply(a[0].to_f,a[2].to_f)}"
when "/"
"#{a[0]} / #{a[2]} = #{Calculator.new.divide(a[0].to_f,a[2].to_f)}"
when "^"
"#{a[0]} to the power #{a[2]} = #Calculator.new.powers(a[0].to_f,a[2].to_f)}"
else
"Not valid"
end
I was thinking of trying to split a string like "234+342" (234 and 342 can be any sized length numbers) into an array such as ["234","+","342"].
But I am stuck on how to do this??? Or is there another way??
Help will be appreciated, just a personal challenge.
Thanks
As you already realized the issue is with the way you are carrying operations over input string.
The simplest way to proceed can be to ask users for two numbers and then ask them to enter the operation needed. Something like:
puts "Enter first number"
a = gets.chomp
puts "Enter second number"
b = gets.chomp
puts "Enter required operation [+, -, *, /]"
c = gets.chomp
You can do this all in one shot too, the way you are already trying, however I would advice against it as you never know what user will enter. Eg:
puts "Enter an expression to be evaluated"
a = gets.chomp # user enters: 123 + 457
# => "123 + 457"
Now extracting number:
numbers = a.scan(/\d+/)
#=> ["123", "457"]
operator = a[/\W+/]
#=> " + "
You can then proceed with your switch case.
I am writing a code that is supposed to read from STDIN exactly n number of times.So lets say 3 times.What is the best way to do that ?
I tried this
counter = 0
while sentence = gets.chomp && counter < 3 do
...
counter += 1
end
but for some strange reason, sentence variable inside loop is Boolean ?
You can do as below:
n.times { sentence = gets.chomp }
or
n.times do
sentence = gets.chomp
# your code here
end
Operator precedence. The line:
while sentence = gets.chomp && counter < 3 do
Is being interpretted as
while sentence = ( gets.chomp && counter < 3 ) do
So, you could do this:
while ( sentence = gets.chomp ) && counter < 3 do
That explains why you got true or false values into sentence, and the third option should fix this, so your code is very close to working. However, it is probably more usual in Ruby to see solutions like Babai's