i’m new at programing. and i was trying to figure out how you add
numbers. or string? here is the coding
puts ‘what is your first name?’
name1= gets.chomp
puts ‘how about your middle?’
name2= gets.chomp
puts ‘and what about your last name?’
name3= gets.chomp
puts 'did you know there are ‘+name1.length+name2.length+name3.length+ ’
letters in your name?’
the problem is i get the strings combined, not adding the seperate
numbers together.
the problem is i get the strings combined, not adding the seperate
numbers together.
help?
name1.length and friends are numbers, not strings. You might have to
you use to_s.
Here’s a fun inject exercise (q means array of questions, a means
array of answers)…
q = [“what is your first name?”, “how about your middle name?”, “and
what about your last name?”]
puts q.inject([]) {|a, i| puts i; a << gets.chomp}.inject(0) {|s, a| s +
a.size}
puts 'did you know there are '+name1.length+name2.length+name3.length+ ’
Here’s a fun inject exercise (q means array of questions, a means
array of answers)…
q = [“what is your first name?”, “how about your middle name?”, “and
what about your last name?”]
puts q.inject([]) {|a, i| puts i; a << gets.chomp}.inject(0) {|s, a| s + a.size}
To comply with your original requirements, that last line should be…
puts ‘did you know there are ’ + q.inject([]) {|a, i| puts i; a <<
gets.chomp}.inject(0) {|s, a| s + a.size}.to_s + ’ letters in your
name?’
Very strange looking, but makes the most logical sense to me.
im not quite sure why it worked though? doesnt it need to be integers to
add together?
(integer + integer + integer).to_s
Inside the parentheses, those are Integer instances being added
together, then the to_s turns the sum into a String object so it will
cooperate with the surrounding strings.
I hope that makes some sense. Sometimes, I don’t even know what I’m
saying
puts 'did you know there are '+name1.length+name2.length+name3.length+ ’
Here’s a fun inject exercise (q means array of questions, a means
array of answers)…
q = [“what is your first name?”, “how about your middle name?”, “and
what about your last name?”]
puts q.inject([]) {|a, i| puts i; a << gets.chomp}.inject(0) {|s, a| s + a.size}
To comply with your original requirements, that last line should be…
puts ‘did you know there are ’ + q.inject([]) {|a, i| puts i; a <<
gets.chomp}.inject(0) {|s, a| s + a.size}.to_s + ’ letters in your
name?’
Very strange looking, but makes the most logical sense to me.
Todd
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.