Why the newline char does not work here? - ruby

def say(arg)
"Hello, #{arg}.\n"
end
say("ABC") # => "Hello, ABC.\n"
Why here \n is printed instead of a newline?

because say returns a String. it doesn't print anything.
If you want to print something you should try:
def say(arg)
puts "Hello, #{arg}.\n"
end

You're most likely trying this in irb which displays the Ruby representation of a string. Compare:
irb(main):007:0> puts say("ABC") + say("ABC")
Hello, ABC.
Hello, ABC.
=> nil
irb(main):008:0> puts "ABC" + "ABC"
ABCABC
=> nil

It is actually never printed to stdio or anything like that, you are simply returning a string from a function.
I'll make the assumption that you are evaluating this in IRB, IRB prints out the result of every expression.
use puts or similar.

Related

Why does "puts 'foo'" and puts "foo\n" result in the same output in Ruby? [duplicate]

This question already has answers here:
Why doesn't puts() print in a single line?
(3 answers)
Closed 5 years ago.
This is from the irb:
irb(main):001:0> puts "abc"
abc
=> nil
irb(main):002:0> puts "abc\n"
abc
=> nil
irb(main):003:0> puts "abc\n\n"
abc
=> nil
As you can see, puts "abc" puts a newline after "abc", as it should. However, puts "abc\n" also puts a single newline, whereas I would expect that there would be two newlines.
To me, the output of puts "abc\n\n" is what I would expect from puts "abc\n".
Why is this the case?
After reading Cary Swoveland's comment I've realized that it is not at all obvious how puts works, because its documentation is quite scarce:
puts(obj, ...) → nil
Equivalent to
$stdout.puts(obj, ...)
It doesn't even bother to explain what $stdout is, nor does it provide a link.
$stdout is one of Ruby's pre-defined global variables. It refers to the standard output which in Ruby happens to be an instance of IO:
$stdout
#=> #<IO:<STDOUT>>
So "Equivalent to $stdout.puts(obj, ...)" means that we have to read the documentation for IO#puts:
Writes the given object(s) to ios. Writes a newline after any that do not already end with a newline sequence. Returns nil.
There you go: puts only adds a newline if the object does not already ends with one.
To get the expected multi-line output, you can simply call puts for each line:
puts 'abc'
or
puts 'abc'
puts
or
puts 'abc'
puts
puts
That's just how puts works. It prevents you from needing to append a newline everytime you call puts.
Given no newline, one will be added
Given a trailing newline, an additional one will not be added
Source: http://ruby-doc.org/core-2.4.1/IO.html#method-i-puts

Ruby `downcase!` returns `nil`

With this code:
input = gets.chomp.downcase!
puts input
if there is at least one uppercase letter in the input, the input will be put on screen, freed of its uppercases. But if the input has no uppercase letter, it will put nil, like if nothing was written.
I want my input to be fully downcased; if it is a string with no uppercase letter, it should return the same string.
I thought about something like this:
input = gets.chomp
if input.include(uppercase) then input.downcase! end
But this doesn't work. I hope someone has an idea on how I should do this.
According to the docs for String:
(emphasis is mine added)
downcase
Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. The operation is locale
insensitive—only characters “A” to “Z” are affected. Note: case
replacement is effective only in ASCII region.
downcase!
Downcases the contents of str, returning nil if no changes were made. Note: case replacement is effective only in ASCII
region.
Basically it says that downcase! (with exclamation mark) will return nil if there is no uppercase letters.
To fix your program:
input = gets.chomp.downcase
puts input
Hope that helped!
This will work:
input = gets.chomp.downcase
puts input
String#downcase
Returns a modified string and leaves the original unmodified.
str = "Hello world!"
str.downcase # => "hello world!"
str # => "Hello world!"
String#downcase!
Modifies the original string, returns nil if no changes were made or returns the new string if a change was made.
str = "Hello world!"
str.downcase! # => "hello world!"
str # => "hello world!"
str.downcase! # => nil
! (bang) methods
It's common for Ruby methods with ! / non-! variants to behave in a similar manner. See this post for an in-depth explanation why.
The reason that downcase! returns nil is so you know whether or not the object was changed. If you're assigning the modified string to another variable, like you are here, you should use downcase instead (without the bang !).
If you're not familiar, the standard library bang methods typically act on the receiver directly. That means this:
foo = "Hello"
foo.downcase!
foo #=> "hello"
Versus this:
foo = "Hello"
bar = foo.downcase
foo #=> "Hello"
bar #=> "hello"

Ruby: Get last character from user input

So I'm trying to find the last character from user input in Ruby.
I've tried the following-
print "Enter in a string: "
user_input = gets
end_char = user_input[-1,1]
puts "#{end_char} is the last char!"
But it returns
" is the last char!".
I've tried
end_char = "test"[-1,1]
and that works as it should (returns t). But its not working when I use user input as the string instead of just typing in a string itself. Help?
So when you say "Enter in a string" and you type "foo", what's the last thing you do? Well you hit enter obviously! So what you actually capture is "foo\n".
Calling user_input[-1,1] actually gives back the \n return symbol which just prints a break return in the output.
print "Enter in a string: "
user_input = gets.chomp
end_char = user_input[-1,1]
puts "#{end_char} is the last char!"
the #chomp method actually removes the return character from the input.
Now when I run it:
stacko % ruby puts.rb
Enter in a string: hi Lupo90
0 is the last char!
Consider this IRB session:
I'll enter "foo":
irb(main):001:0> user_input = gets
foo
"foo\n"
I entered "foo", and to terminate the input I had to press Return (or Enter depending on the OS and keyboard), which is the "\n" (or "\r\n") line-ending, depending on whether your OS is *nix or Windows.
Looking at what I entered:
irb(main):002:0> user_input[-1]
"\n"
Here's what is output. Notice that the single-quotes are on separate lines because a "\n" is a new-line character:
irb(main):003:0> puts "'\n'"
'
'
nil
(The trailing nil is the result of puts and isn't important for this example.)
So, gets returned everything entered, including the trailing new-line. Let's fix that:
irb(main):004:0> user_input = gets.chomp
foo
"foo"
irb(main):005:0> user_input[-1]
"o"
irb(main):006:0> puts '"%s" is the last char' % [user_input[-1]]
"o" is the last char
chomp is used to strip trailing line-end from the end of a string:
irb(main):010:0> "foo\n".chomp
"foo"
irb(main):011:0> "foo\r\n".chomp
"foo"
This is a really common question on Stack Overflow. Perhaps searching for it would have helped?

What is the differences between print and puts in Ruby with example?

May be this is a duplicate question, What is the differences between print and puts in Ruby? Can I have answer with example please?
print does not add a newline at the end.. puts does.
Most other languages have similar structures too.
Java has System.out.println() and System.out.print()
C# has Console.WriteLine() and Console.Write()
Pascal had Writeln() and Write()
It's simple. puts automatically appends a newline when it prints. print prints the string without modification.
Another difference is in the number of underlying write operations. puts is (roughly) equivalent to:
STDOUT.write(str)
STDOUT.write("\n")
And print (roughly) equivalent to:
STDOUT.write(str)
So, in multithreaded environments, puts can create some weird looking stuff, like this:
Message1Messa
ge2
(blank line)
While printing a string with a concatenated newline yields:
Message1
Message2
Other than that, they're the same.
irb(main):014:0> class Person
irb(main):015:1> attr_accessor :name, :age, :gender
irb(main):016:1> end
=> nil
irb(main):017:0> person = Person.new
=> #<Person:0x2bf03e0>
irb(main):018:0> person.name = "Robert"
=> "Robert"
irb(main):019:0> person.age = 52
=> 52
irb(main):020:0> person.gender = "male"
=> "male"
irb(main):021:0> puts person
#<Person:0x2bf03e0>
=> nil
irb(main):022:0> print person
#<Person:0x2bf03e0>=> nil
irb(main):023:0> print person.name
Robert=> nil
irb(main):024:0> puts person.name
Robert
=> nil
The difference between print and puts is that puts automatically moves the output cursor to the next line (that is, it adds a newline character to start a new line unless the string already ends with a newline), whereas print continues printing text onto the same line as the previous time.
puts isn't prefixed by the name of a class or object upon which to complete the method and puts is a method made available from the Kernel module and that is included and searched by default, so usually you won’t need to use Kernel.puts to refer to it.
Kernel.puts "Hello, world!"
puts takes only one argument and is rarely followed by other methods or logic, so parentheses are not strictly necessary.
There are two major differences between puts and print in general.
1. New line
puts take every element and prints in a newline(without specifying the need of a new line character "\n" in the end)
Whereas print doesn't print each element in a new line unless the programmer explicitly specify it.
puts "Hello, Welcome to Ruby"
Output:
Hello, Welcome to Ruby
Dell-System-XPS:~/Documents/2016RoR/Ruby$
print "Hello, Welcome to Ruby"
Output:
Hello, Welcome to RubyDell-System-XPS:~/Documents/2016RoR/Ruby$
Did you notice, there is no new line after the output.
However, the new line should work when you explicitly mention the new line character like below
print "Hello, Welcome to Ruby \n"
Output:
Hello, Welcome to Ruby
Dell-System-XPS:~/Documents/2016RoR/Ruby$
2. Empty characters or NIL values
print statement prints the empty or NIL values but puts statement doesn't print them if they contain NIL values in it.
> print [nil, 33,44,55]
> [nil, 33, 44, 55] => nil
> puts [nil, 33,44,55]
> 33
> 44
> 55
=> nil
"You see the difference, there is no NIL value printed while using puts"
A comparison can be see in print vs put. For example take a look on Input & output in Ruby.

Why does ruby output values like this?

Fairly new to ruby, can someone explain why these 2 things respond differently?
a=["A","B","C"]
puts a
A
B
C
puts "#{a}"
ABC
a.to_s returns the same output as the templating output, but shouldn't the simple "puts a" do the same?
The specified behavior of puts is that it writes stuff out with a newline afterwards. If it's an array, it writes each element with a newline.
When you do puts a.to_s, it does the to_s first (resulting in a single string) and then outputs that single string with a newline afterward.
As discussed in this thread, and for no good reason, Arrays have magically inconsistent behavior when given to puts.
array.each {|e| puts e }
is the same as:
puts array

Resources