Programming Fundamentals/Strings/Ruby

strings.rb

edit
# This program splits a given comma-separated name into first and last name
# components and then displays the name.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikibooks.org/wiki/Ruby_Programming

def get_name()
    while true
        puts("Enter name (last, first):\n")
        name = gets.chomp
        index = name.index(",")
        if index != nil
            break
        end
    end
    return name
end

def get_last(name)
    index = name.index(",")
    if index < 0
        last = ""
    else
        last = name[0..index - 1]
    end
    return last
end

def get_first(name)
    index = name.index(",")
    if index < 0
        first = ""
    else
        first = name[index + 1..name.length]
        first = first.strip();
    end
    return first
end

def display_name(first, last)
    puts("Hello " + first + " " + last + "!")
end

def main()
    name = get_name()
    last = get_last(name)
    first = get_first(name)
    display_name(first, last)
end
    
main()

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own Ruby compiler / interpreter / IDE.

See Also

edit