Beginner 'How-to' Question on getting Array info


#1

Hi,

I am trying to learn ruby and had a question (multiple in fact, however,
i’ll ask this one)

Im making a tiny script that asks for the names of a person’s children,
then replies by saying hi to each child.

for example:

what’s the names of these precious babies?
user types: John, Greg, Sam
replies: Hi John, Hi Greg, Hi Sam.

so far I was working with a single person, but I understood that part:
def welcome(name)
result = "Hey, " + name
end
puts “hey what’s your name?”
name = gets
puts welcome(name)

any help would be great ;] hope it’s as easy as it sounds!


#2

Nouman S. wrote:

what’s the names of these precious babies?

any help would be great ;] hope it’s as easy as it sounds!

def welcome(name)
result = "Hey, " + name
end

str = ‘init’
children = []
while !str.empty?
puts “Hey, what’s your name?”
str = gets.chomp
children << str unless str.empty?
end

children.each { |child| puts welcome(child) }

That will do it. Hit enter without any chars to finish typing names…

=======================================================================
This email, including any attachments, is only for the intended
addressee. It is subject to copyright, is confidential and may be
the subject of legal or other privilege, none of which is waived or
lost by reason of this transmission.
If the receiver is not the intended addressee, please accept our
apologies, notify us by return, delete all copies and perform no
other act on the email.
Unfortunately, we cannot warrant that the email has not been
altered or corrupted during transmission.


#3

thanks for taking the time to help Michael, this works great. Now time
to break it down and see how you did it :slight_smile:

thanks again!


#4

On Tue, Apr 7, 2009 at 6:53 PM, Nouman S. removed_email_address@domain.invalid
wrote:

thanks for taking the time to help Michael, this works great. Now time
to break it down and see how you did it :slight_smile:

thanks again!

Here’s one for you that uses some other methods…

puts “What are the kids’ names?”
puts( gets.chomp.split.map {|n| “Hi #{n}”}.join(", ") )

… basically, #split method builds array, #map changes prepends each
element with "Hi ", and #join builds a string separating each element
with ", ".

This assumes the user doesn’t use commas to separate names. If they
do, you can split on commas with split(","), or use regular
expressions.

Todd