How can I check if a variable is a number?
I'm trying this:
set a to 5
if a is a number
display dialog "Yes! It's a number!"
end if
I've also tried this code:
set a to 5
if a is integer
display dialog "Yes! It's a number!"
end if
But unfortunately it doesn't work as expected.
set a to 5
if class of a is integer then
display dialog "Yes! It's a number!"
end if
class of a is integer will fail if you use
set a to "5"
This will work if even if the variable is a number but was entered as text.
set a to "5"
try
set a to a as number
display dialog "Yes! It's a number!"
end try
This is my solution:
on is_number(number_string)
try
set number_string to number_string as number
return true
on error
return false
end try
end is_number
Related
I am trying to solve the "24" game. The point of the game is to generate 4 random integers from 1-9 and ask the player to use addition, subtraction, multiplication, or division to get the number 24. My code runs fine until a player enters a number, and then I get "Command not found". Can someone please take a look at this:
def evaluate (input,solved_v)
input = eval (input.to_f)
#convert to a float and then evaluates it; it computes
if input == 24
solved_v = true
puts "great job! you did it!"
else
puts "please try again"
end
end
def test_entry (input)
if input.scan(%r{[^\d\s()+*/-]}).empty?
#this scan detects letters and special characters because only numbers work
true
else
false
end
end
puts
puts "try to use +, -, / or * to"
puts "get 24 from the integers provided"
puts
series = (1..4).collect{ rand(1..9)}
#generates 4 random numbers between 1 and 9
for i in series
puts i
end
puts "Please guess"
solved = false
unless solved = true
user_input = gets.chomp
if test_entry(user_input) == true
evaluate(user_input)
else
puts "invalid characters entered"
puts "please try again"
puts
end
end
There are numerous problems with your program.
Don't put spaces between your method names and parentheses.
eval takes a string argument, not a float.
Ruby passes arguments by value, so solved_v isn't going to get
returned. Make it the return value of your evaluate method. I'd also
suggest renaming your methods to express their boolean intent. See below...
Don't check boolean expressions for equality to true or false, just use them.
def correct?(input)
if eval(input) == 24
puts "great job! you did it!"
true
else
puts "please try again"
false
end
end
def good_entry?(input)
input.scan(%r{[^\d\s()+*/-]}).empty?
end
and they get used as follows
while true
user_input = gets.chomp
if good_entry?(user_input)
break if correct?(user_input)
else
...
end
end
Finally, note that you're not actually checking that the input provided by the user uses only the supplied random numbers.
My current code is this:
print "Feed me input."
def get_input
input_value=gets.chomp
if !input_value
print "you didn't type anything"
else
input_value.downcase!
if input_value.include? "s"
input_value.gsub!(/s/,"th")
else
print "You entered a string but it had no 's' letters."
end
end
return input_value
end
get_input()
if !get_input
get_input
else
puts "#{get_input}"
end
I'm not sure why it isn't working. When I run it I get prompted for input then when I press enter after entering none I get the "You entered a string but it had no 's' letters", not the "you didn't type anything" that I wanted.
Every object except false and nil is treated as false if they are used as predicates. Even empty string is treated as true:
s = ""
puts true if s # => true
Use String#empty? to check if it is empty string.
As you said When I run it I get prompted for input then when I press enter after entering none - It means what happened acctually is
input_value="\n".chomp #( you gets methods take only `\n` as input)
"\n".chomp # => ""
so your input_value variable holds and empty string object. Now in Ruby every object has true value, except nil and false. Said that "" is also true,but you did !input_value,which means you are making it false explicitly. That's the reason in the below if-else block, else part has been executed and you didn't see the expected output "you didn't type anything".
if !input_value
print "you didn't type anything"
else
input_value.downcase!
if input_value.include? "s"
#.. rest code.
So I would suggest you in such a context replace the line if !input_value to if input_value.empty?, Which will make your code to behave as you are expecting. I didn't take your logic as a whole,but tries to show you how to code to meet your needs:
print "Feed me input."
def get_input
input_value=gets.chomp
if input_value.empty?
puts "you didn't type anything"
false
else
puts "found value"
input_value.downcase!
end
end
until input = get_input
# code
end
puts input
output
kirti#kirti-Aspire-5733Z:~/Ruby$ ruby test.rb
Feed me input.
you didn't type anything
you didn't type anything
you didn't type anything
HH
found value
hh
kirti#kirti-Aspire-5733Z:~/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)
I know this is sloppy code, but here it is:
display dialog ("Start Screensaver. Please type: matrix, coffee, waffles, star, water, or
fireworks.", default answer "")
if text returned of result = "matrix" then
set user_choice to "MatrixSaver"
else
if text returned of result = "coffee" then
set user_choice to "Coffee"
else
if text returned of result = "waffles" then
set user_choice to "Waffles"
else
if text returned of result = "star" then
set user_choice to "Hyperspace"
else
if text returned of result = "water" then
set user_choice to "LotsaWater"
else
if text returned of result = "fireworks" then
set user_choice to "Skyrocket"
else
(*do nothing*)
end if
end if
end if
end if
end if
end if
if (user_choice = null) then (*do nothing*)
else
tell application "System Events"
set ss to screen saver user_choice
start ss
end tell
end if
When I'm trying to compile my code, the 'default answer' Is highlighted, and it says: "Expected “)”, etc. but found identifier."
Any Ideas? Thanks.
I believe the correct syntax is just
display dialog "Start Screensaver. Please ..." default answer ""
The , between the ("Start Screensaver") and the default answer parameter is causing the syntax error. Remove the ,.
This isn't a syntax error, but the variable user_choice doesn't exist outside of the big if block. If you ran it as written, you would get this message at the last if block:
The variable user_choice is not defined.
You could fix this by declaring the variable before the display dialog statement...
set the user_choice to ""
Now you can use the variable anywhere in the code. :)
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