Assigning a value to a variable - ruby

I would like the variable size to be defined in my program via user input. I have been unsuccessful in defining it in any way other than by a number manually entered into my code (currently 10).
def pass (size = 10)

This works for me:
def pass(size)
puts size
end
puts "please input a number:"
size = gets
pass(size)

You may need to use to_i, as your user input is a string. Then it works as the previous answer:
def pass(size = 10)
size = size.to_i
puts "It's a number! #{size}" if size.is_a? Integer
end
puts "please input a number:"
size = gets
pass(size)

Related

Generate largest number of 10 inputs

New to scripting here. Basically, I am needing to write a program to accept 10 input numbers and return the largest in the list.
I have this code, but obviously it is not running:
class Generator
def getNumbers
number = Array.new
puts "To begin, You will need to enter your numbers."
print "Press Enter to continue."
Console_Screen.pause
10.times do
print "\nPlease enter any number: "
input = STDIN.gets
input.chop!
list.push
return list
end
list.push(number)
print list.max
end
end
Console_Screen.new
Find = Generator.new
end
Can anyone help me with what I coded incorrectly?
There are many problems with your code. Among them I may point:
1) You created an array named number to store your numbers and then tried to push them to another variable named list;
2) As #tadman pointed, you used a return inside a times block and this makes the block to be executed only once;
3) You never invoked getNumbers to make your process really happen!
This code would do what you need:
class Generator
def get_numbers
numbers = Array.new
puts "To begin, You will need to enter your numbers."
puts
10.times do
print "\nPlease enter any number: "
input = STDIN.gets
input.chop!
numbers.push(input.to_i)
end
print numbers.max
end
end
Find = Generator.new
Find.get_numbers
Notice that I changed the name of your method from getNumbers to get_numbers, which is much more Ruby-like.
Notice that I also changed the name of your array from number to numbers, 'cause it will store numbers, not a single number. Naming your varables correctly may help you to think correctly about your problem. It also helps when it comes for other people reading your program. Even you, six months later, will have problems to understand your own code if you don't name things correctly an comment you code well.
By the way, I also pushed the numbers to numbers as integer, using #to_i. This will make the numbers be compared as numbers, not as strings. If you researsh a bit you'll find out this could be a bit different. If someone enters 0300 as a number, it will be considered to be smaller then 200 as string, but when converted to integers, they will be in the correct order.
Consider this approach perhaps:
#script.rb
nums = []
10.times do |c|
puts "enter number #{c+1}"
nums << gets.to_i
end
puts "max number is #{nums.max}"
Example
$ ruby script.rb
enter number 1
#5
enter number 2
#3
enter number 3
#66
enter number 4
#4
enter number 5
#3
enter number 6
#2
enter number 7
#1
enter number 8
#6
enter number 9
#9
enter number 10
#0
#max number is 66
I had the same assignment and this is what I ended up creating. (I had to get a little more involved with input control and I'm sure there's easier ways of doing this. Also had to utilize the variables as part of the grade. I assume to prevent me from ripping off the code above.)
class Screen
def cls
puts ("\n" * 25)
puts "\a"
end
def pause
STDIN.gets
end
end
Console_Screen = Screen.new
num = [] #array to store user input
$counter = 1
loop do
puts "Please enter number " + $counter.to_s + " of a series of 10 numbers in order to determine the largest."
# Console_Screen.pause
loop do
print "Enter Number Here:"
number = gets.chomp
num << number.to_i if number =~ /[0-9]/ #only writes to the array if it's a number
break if number =~ /[0-9]/ #only allow numbers
end
$counter += 1
break if $counter == 11
end
puts "Press Enter to have your numbers sorted and the largest presented to you."
Console_Screen.pause
largest = num.max
puts "This is your largest number: " + largest.to_s
Console_Screen.pause

How to make Ruby sleep for amount input by user?

I've tried to make Ruby sleep for an amount that the user has input by doing this:
puts "Time?"
time = gets.chomp
time.to_i
sleep(time)
Does anyone know what I'm trying to do and what I'm doing wrong?
The following works for me:
puts "Time?"
time = gets.chomp
sleep(time.to_i)
.to_i doesn't convert the value and overrides the variable, it simply returns the converted result. So it needs to either be used directly in the sleep argument or set its own (or another variable):
time = time.to_i
sleep(time)
Calling time.to_i returns an integer, but doesn't change time itself. Therefore time is still a string.
Change it to:
puts 'Time?'
string = gets.chomp
time = string.to_i
sleep(time)
Because to_i doesn't care if there is a "\n" at the end of the string, you can skip the chomp call. Therefore you can just write:
puts 'Time?'
time = gets.to_i
sleep(time)

How to use simple operator on this?

I'm create some sample code and still begineer
class Number
def initialize(name)
#first = []
#second = []
#final = 0
end
def input
print "Please input first number"
#first = gets.chomp
print "Please input second number"
#second = gets.chomp
end
def output
#final = #first * #second
puts #final
end
end
number = Number.new('Jakz')
number.class
number.input
number.output
I want to sum the 2 input number but its give error because the 2 number become a string not a number.How to fix it?
gets returns a String. The prompt does not know that you are requesting a number. Calling to_f does its best to convert the string to a floating point number
def input
print "Please input first number"
#first = gets.chomp.to_f
print "Please input second number"
#second = gets.chomp.to_f
end
be aware that if the user enters something that is not a number - the above code does not validate it, and will most probably set the variables to 0.

Program to take input from command line into an array and find the biggest among them

I am new to Ruby and just can't figure out how you take input for an array from a user and display it.If anyone could clear that I can add my logic to find the biggest number.
#!/usr/bin/ruby
puts "Enter the size of the array"
n = gets.chomp.to_i
puts "enter the array elements"
variable1=Array.new(n)
for i in (0..n)
variable1[i]=gets.chomp.to_i
end
for i in (0..n)
puts variable1
end
How about capturing the array in one line?
#!/usr/bin/ruby
puts "Enter a list of numbers"
list = gets # Input something like "1 2 3 4" or "3, 5, 6, 1"
max = list.split.map(&:to_i).max
puts "The largest number is: #{max}"
You are doing it ok. But try this little change
#!/usr/bin/ruby
puts "Enter the size of the array"
n = (gets.chomp.to_i - 1)
puts "enter the array elements"
variable1=Array.new(n)
for i in (0..n)
variable1[i]=gets.chomp.to_i
end
puts variable1
or for undefined number of values here is one way
#!/usr/bin/ruby
puts "enter the array elements (type 'done' to get out)"
input = gets.chomp
arr = []
while input != 'done'
arr << input.to_i
input = gets.chomp
end
puts arr
I believe that this is a little bit more elegant solution.
puts "Please enter numbers separated by spaces:"
s = gets
a = s.split(" ")
#Displays array
puts a
#Displays max element
puts a.max
First you collect the series of numbers from the user, then you use a split method on the string, which converts it to the array. If you want to use some other separator, like "," than you can write s.split(","). After that you can use your logic to find the biggest number or you could just use max method.
Some feedback:
chomp.to_i is a bit redundant, since the latter will also remove newlines.
for x in y is not commonly seen in idiomatic Ruby code. It basically behaves like each with slightly different scoping rules and probably should have been removed from the language a while ago.
Ruby arrays are dynamic, so no need to preinitialize them. Something like (1..n).map { gets.to_i } would also produce the array you need.
Displaying it can then be done like this: array.each { |n| puts n }
Alternatively you can use the strip approach outlined before, take the numbers as command line arguments in ARGV or pipe into your program using ARGF.

elegant way to check if a string inputed by user is an integer in ruby?

I'm trying to validate that the input a user gives my program via gets is an integer. is_a?(Integer) does not work, as far as i can tell, because gets gets a string from the user, so it will always return false even if the user enters an valid integer (in string form). One would think I could simply use to_i on the input and be done with it, but that raises another issue - "75akjfas".to_i results in 75. So if I relied on to_i to solve my problems, anything starting with numbers will work.
How do I cleanly validate that the value is an integer only, and not a combination of numbers and letters? Or do I need to resort to regex for this?
print "Enter an integer (or try to sneak by something other): "
puts Integer(gets) rescue puts "Hey, that's not an integer!"
How about s.to_i.to_s == s? I'd prefer regex however.
Using regex you could do it like this:
class String
def integer?
!!(self =~ /^[-+]?[0-9]+$/)
end
end
You could use Integer() but you need to be careful with hex, binary, or octal input. http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-Integer
def valid_integer?(string)
begin
!!Integer(string)
rescue ArgumentError
false
end
end
Check this code example for how to use the checked string input by the user
puts "Enter a number: "
user_input = gets.chomp
check = (user_input.to_i.to_s == user_input)
while (!check ) do
puts("Wrong Input, Pls, Enter a number: " )
user_input = gets.chomp
check = (user_input.to_i.to_s == user_input)
end
if user_input.to_i < 0
puts "Number is negative"
elsif user_input.to_i > 0
puts "Number is positve"
else
puts "Number is Zero"
end
Ruby can do it without esoteric solutions:
Integer is a integer
1970.is_a?Integer
true
String is not a integer
"1970".is_a?Integer
false
String to integer is a integer
"1970".to_i.is_a?Integer
true

Resources