How to display display numeric value as string in ruby? - ruby

def sumof
s = 12 + 17
puts "The sum of 12 and 17 is: " + s
end
When I call sumof, I'm getting an error
Thanks for helping

There is really one way to convert to a string, but it can be used in multiple ways. The method is called to_s (to string).
Way 1 (manual):
"Some string " + num.to_s
Way 2 (interpolation):
"Some string #{num}"

You're going to want to do
"The sum is " + s.to_s OR "The sum is #{s}"
the problem being that conversion to string is not implicitly done in your original example.

Related

Write a program which gets a number from a user and identify whether it is an Integer or a Float in ruby

I am trying this :
print " Enter Value "
num = gets.chomp
also tried .kind_of? but didn't work
if num.is_a? Float
print " Number is in float "
also tried .kind_of? but didn't work
else num.is_a? Integer
print " Number is in integer "
end
Your problem here is that gets returns a String you can actually determine this based on the fact that you are chaining String#chomp, which removes the trailing "separator" which by default is return characters (newlines) e.g.
num = gets.chomp # User enters 1
#=> "1"
In order to turn this String into a Numeric you could explicitly cast it via to_i or to_f however you are trying to determine which one it is.
Given this requirement I would recommend the usage of Kernel#Integer and Kernel#Float as these methods are strict about how they handle this conversion. knowing this we can change your code to
print " Enter Value "
num = gets.chomp
if Integer(num, exception: false)
puts "#{num} is an Integer"
elsif Float(num, exception: false)
puts "#{num} is a Float"
else
puts "#{num} is neither an Integer or a Float"
end
Note: the use of exception: false causes these methods to return nil if the String cannot be converted to the desired object, without it both methods will raise an ArgumentError. Additionally when I say these methods are strict about conversion a simple example would be Integer("1.0") #=> ArgumentError because while 1 == 1.0, 1.0 itself is a Float and thus not an Integer
Some examples:
num = 6.6
num.is_a?(Integer)
=> false
num.is_a?(Float)
=> true
num = 6
num.is_a?(Integer)
=> true
num.is_a?(Float)
=> false
Minor note, #print is not the correct method to print to the screen. The correct method is #puts.
So your code would look like this:
if num.is_a?(Float)
puts 'Number is a float.'
elsif num.is_a?(Integer)
puts 'Number is an integer.'
else
puts 'Number is neither a float nor an integer.'
end
I suspect #gets returns a string though, which means you'll need to convert from a string into a numeric first.

Converting math expression to string in Ruby

problem = 7 + 3
puts problem.to_s
I'm new to Ruby. The code above returns 10. How do I get 7 + 3 as the output, without assigning it to problem as a string in the first place? Am I missing something extremely simple?
Am I missing something extremely simple?
Yes, you are. This is impossible. 7 + 3, as an arbitrary expression, is evaluated/"reduced" to 10 when it's assigned to problem. And the original sequence of calculations is lost.
So you either have to start with strings ("7 + 3") and eval them when you need the numeric result (as #zswqa suggested).
Or package them as procs and use something like method_source.
just for fun (don't try at home)
class Integer
def +(other)
"#{self} + #{other}"
end
end
problem = 7 + 3
puts problem.to_s # "7 + 3"
7 is Fixnum (ruby < 2.4) or Integer (ruby >= 2.4)
"7" is String
So you need to define for ruby what you need because + for Integer is addition, + for String is concatenation:
problem = "7" "+" "3"
That is equal to:
problem = "7+3"

How do I add one more year to the given input?

I want to get an output so that it adds one more year to an age input.
This is my code:
print "Age: "
age = gets.chomp.to_i
def age_next_year(int)
age.each do |int|
int += 1
end
puts "Next year I’ll be " + age_next_year(age)
I can't seem to get the correct output.
You don’t need to call each since it’s designed to iterate arrays and you have an integer. Also, you don’t need to reassign the value back to int local variable, just return it from the method:
def age_next_year(int)
int + 1
end
Another issue is you are trying to + what age_next_year method returns (integer) to the string. The explicit conversion is required there:
puts "Next year I’ll be " + age_next_year(age).to_s
I'm just asking, but why don't you do something like this:
print "Age: "
age = gets.chomp.to_i + 1
printf "Next year I'll be %d\n", age
# OR
puts "Next year I'll be " + age.to_s
It works fine for me, and it's smaller and quicker than what you did.

what does #{ do in Ruby? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Meaning of #{ } in Ruby?
I know it is used for meta-programming, and I'm having a hard time trying to wrap my mind about what this operator is doing in the following example:
class Class
def attr_accessor_with_history(attr_name)
attr_name = attr_name.to_s # make sure it's a string
attr_reader attr_name
attr_reader attr_name+"_history"
class_eval %Q"
def #{attr_name}=(value)
if !defined? ##{attr_name}_history
##{attr_name}_history = [##{attr_name}]
end
##{attr_name} = value
##{attr_name}_history << value
end
"
end
end
class Foo
attr_accessor_with_history :bar
end
In general terms, #{...} evaluates whatever's inside of it and returns that, converted to a string with to_s. This makes it a lot easier to combine several things in a single string.
A typical example:
"There are #{n} car#{n == 1 ? '' : 's'} in the #{s}"
This is equivalent to:
"There are " + n.to_s + " car" + (n == 1 ? '' : 's').to_s + " in the " + s.to+_s
It's important to remember that the contents of the #{...} interpolation is actually a block of Ruby code and the result of it will be converted to a string before being combined.
That example of meta programming is awfully lazy as instance_variable_get and instance_variable_set could've been used and eval could've been avoided. Most of the time you'll see string interpolation used to create strings, not methods or classes.
There's a more robust formatter with the String#% method:
"There are %d car%s in the %s" % [ n, (n == 1 ? '' : 's'), s ]
This can be used to add a precise number of decimal places, pad strings with spaces, and other useful things.
#{var} does variable substitution in Ruby. For example:
var = "Hello, my name is #{name}"
The code you've posted is generating a string with the code for an accessor method for the attr_name you've passed in.
It's not doing much really :D. All the red text is basically just a string. The "bla #{var} bla" part is just a nicer way of writing "bla " + var + " bla". Try it yourself in irb:
a = 10
puts "The Joker stole #{a} pies."
what it does is called variable interpolation.
name = "Bond"
p "The name is #{name}. James #{name}."
will output,
> "The name is Bond. James Bond."

Ruby gets/puts only for strings?

I'm new to Ruby and am currently working on some practice code which looks like the following:
puts 'Hello there, Can you tell me your favourite number?'
num = gets.chomp
puts 'Your favourite number is ' + num + '?'
puts 'Well its not bad but ' + num * 10 + ' is literally 10 times better!'
This code however just puts ten copies of the num variable and doesn't actually multiply the number so I assume I need to make the 'num' variable an integer? I've had no success with this so can anyone show me where I'm going wrong please?
If you are using to_i, then chomp before that is redundant. So you can do:
puts 'Hello there, Can you tell me your favourite number?'
num = gets.to_i
puts 'Your favourite number is ' + num.to_s + '?'
puts 'Well its not bad but ' + (num * 10).to_s + ' is literally 10 times better!'
But generally, using "#{}" is better since you do not have to care about to_s, and it runs faster, and is easier to see. The method String#+ is particularly very slow.
puts 'Hello there, Can you tell me your favourite number?'
num = gets.to_i
puts "Your favourite number is #{num}?"
puts "Well its not bad but #{num * 10} is literally 10 times better!"
Use the to_i method to convert it to an integer. In other words, change this:
num = gets.chomp
To this:
num = gets.chomp.to_i
you can also make sure the number that the user is using is an integer this way:
num = Integer(gets.chomp)
but you have to create a way to catch the error in case the user input otherwise like a char, or string so; it is must better to use:
num = gets.chomp.to_i
In case the user put another type of data, num will be equal to 0 like you can see in this test example:
puts "give me a number:"
num = gets.chomp.to_i
if num >3
puts "#{num} es mayor a 3 "
else
puts "#{num} es menor a 3 o 3"
end
This a example of the interaction with that script:
give me a number:
sggd
0 es menor a 3 o 3
nil
I hope this clarify better your point.
I wrote a similar program as yours. Here is how I finally got it to work properly! I had to assign the favorite number to be an integer. Then, in the next line I set the new_fav_num with the value of fav_num +1 and then converted it to string. After that, you can just plug your code into the return statement that you want to say to the user, only you have to convert the first fav_num to a string.
puts "What is your favorite number?"
fav_num = gets.chomp.to_i
new_fav_num = (fav_num + 1).to_s
puts "Your favorite number is " + fav_num.to_s + ". That's not bad, but " +
new_fav_num + " is bigger and better!"
Hope this helps.

Resources