In raw_input() appears at the end "none" - python-2.x

By printing out of raw_input() appears at the end a "none".
I defined above a function to look nice when printing the question.
Here's my code:
def delay_print_input(string):
for c in string:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.15)
ans=raw_input(delay_print_input("What do you want?\n>> "))
The output looks like:
What do you want?
>> None
My question is, how can I remove this none?

Your function returns None, which raw_input then prints. What you want is this:
def delay_print_input(string):
for c in string:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.15)
delay_print_input("What do you want?\n>> ")
ans=raw_input()

Your function is returning None and sending it to the input function. You can just return a blank string in your function
def delay_print_input(string):
for c in string:
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(0.15)
return ""

Related

.include? is not triggered when reading a txt file

I am under the impression that the following code should return either the search item word or the message no match - as indicated by the ternary operator. I can't diagnose where/why include? method doesn't work.
class Foo
def initialize(word)
#word=word
end
def file_open
IO.foreach('some_file.txt') do |line|
line.include?(#word) ? "#{#word}" : "no match"
end
end
end
print "search for: "
input = gets.chomp.downcase
x = Foo.new(input)
puts x.file_open
The input exists in some_file.txt. My ternary operator syntax is also correct. IO reads the text fine (I also tried File.open() and had the same problem). So I must be making a mistake with my include? method.
You need to control the returned value. file_open defined above will always return nil. The ternary will be executed properly, but nothing is done with its value. Instead you can do the following:
class Foo
def initialize(word)
#word=word
end
def file_open
IO.foreach('some_file.txt') do |line|
return line if line.include?(#word)
end
return "no match"
end
end

Making a sorted array of user's input

I'm learning Ruby with 'Learn to Program' by Chris Pine. On chapter 10 I should write a program where the user types as many words as he like and when he's done, he can just press Enter on an empty line and exit.
I came up with this:
puts "Type whatever you want!"
index = 0
word = ''
array = []
while word != nil
word << gets.chomp
array[index] = word
index = index + 1
end
puts ''
puts array.sort
But that doesn't work. What did I miss? Is there another way I could define word without having to repeat it?
The word will not have nil value. It will be an empty string. So you need to check for that:
while word != ""
# or even better
while !word.empty?
Also, you are adding everything to your word. You probably want to assign to it instead:
word = gets.chomp
Per author's comment:
begin
# your code here
end while !word.empty?
# OR more readable
begin
# your code here
end until word.empty?
It seems like there's a simpler solution, if I'm reading the question correctly.
You could do something like this:
user_input = gets.chomp.split(" ").sort
ex)
input: bananas clementine zebra tree house plane mine
output: ["bananas", "clementine", "house", "mine", "plane", "tree", "zebra"]
Here's a simple loop that you could do just for kicks:
arr = []
arr << $_.strip until gets =~ /^\s*$/
puts arr.sort
$_ is a special variable that evaluates to the last input read from STDIN. So basically this reads "Call gets and check if the input is just spaces. If it is then break out of the loop, otherwise append the last input with whitespace removed value onto the array and continue looping."
Or even more fun, a one liner:
puts [].tap {|arr| arr << $_.strip until gets =~ /^\s*$/}.sort
Basically same thing as above except using tap to initialize the variable.
To answer your questions:
Is there another way I could define word without having to repeat it?
Use side effects of assignment. In ruby when you assign a variable the return value of that assignment is the assigned variable, as in:
irb(main):001:0> (variable = 2) == 2
=> true
The idea would be to put the assignment in the your conditional. If I were to write something like this in a comprehensible loop, as opposed to those above, I'd write something like this:
arr = []
while !(word = gets.strip).empty?
arr << word
end
puts arr.sort
Using loop might simplify the code:
a = []
loop do
input = gets.chomp
if input.empty?
break
else
a << input
end
end
a.sort!
puts a

Return doesn't output the method to the console

When I call the greeter method, it doesn't output the string to the console. I'm having a hard time understanding why. Can anyone help?
def greeter(name)
return "Hello #{name}!!"
end
def by_three?(num)
if num % 3 == 0
puts true
else
puts false
end
end
greeter("Michael")
by_three?(4)
return returns value from method, but doesn't print it. You need:
puts greeter("Michael")
Also you don't need this return, at all, method returns value of the last executed line.

Error when chaining with chomp

I wrote a small program as the following
print "Your string = "
input = gets.chomp.downcase!
if input.include? "s"
puts "Go yourself!"
end
But I got the error
undefined method `include?' for nil:NilClass (NoMethodError)
if I delete the exclamation mark (!) after downcase, the program runs properly.
I don't understand the reason.
String#downcase! will give you nil, if the string is already in down-cased. So use String#downcase, it is safe. I am sure, you passed from the command line to the method gets, a string which is already down-cased. Replace the line input = gets.chomp.downcase! with input = gets.chomp.downcase. Now you are safe.
String#downcase
Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. If the receiver string object is already, downcased, then the receiver will be returned.
String#downcase!
Downcases the contents of str, returning nil if no changes were made.
One example to demonstrate this -
>> s = "abc"
>> p s.downcase
"abc"
>> p s.downcase!
nil
Now nil is an instance of the class NilClass, which has no instance method called #include?. So you got no method error. This is obvious.
>> nil.respond_to?(:downcase)
false
>> nil.respond_to?(:downcase!)
false
>> s.respond_to?(:downcase!)
true
>> s.respond_to?(:downcase)
true
Do not use downcase! as it can return nil if no changes have been made to the string.
Therefore, the correct code will be:
print "Your string = "
input = gets.chomp.downcase
if input.include? "s"
puts "Go yourself!"
end

Why does Kernel#p duplicate my text on standard output?

Look at this code :
def hello
p "Hey!"
end
p hello
the output will be:
"Hey!"
"Hey!"
=> "Hey!"
And so here is my conclusion: puts itself returns the text which is going to be sent in output in Ruby code, else it wouldn't print "Hey!" again. What is happening while printing the string? If puts doesn't send it to standard output directly, who is responsible for it and how?
All Methods Return a Value
In Ruby, almost everything returns a value, even if that value is nil. However, in your case the issue is that Kernel#p and Kernel#puts differ in the values they return.
def hello
# Print string literal, then return
# the printed object.
p "Hey!"
end
# Print the return value of main#hello.
p hello
As a result, the string gets printed once inside the method, and then the method's return value is passed to Kernel#p and printed again. This is by design.
Use Kernel#puts to Avoid Duplicated Output
def hello
# Print string; return nil.
puts "Hey!"
end
# Calls main#hello, but prints nil (blank line).
puts hello
This will result in the string literal being printed inside the method, and then a blank line printed since the return value from the method is nil.
Hey!
=> nil
The Right Way
If you want to avoid the blank line, avoid sending to standard output more than once. For example:
def hello
'Hey!'
end
p hello
If the p method returns the string it's given, then hello would return that as well, which means that the secondary p call would repeat it.
This is probably why puts returns nil by default.

Resources