Programming Fundamentals/Strings/Ruby: Difference between revisions

From Wikiversity
Jump to navigation Jump to search
Content deleted Content added
Creating
(No difference)

Revision as of 14:23, 26 February 2017

strings.rs

# This program splits a given comma-separated name into first and last name
# components and then displays the name.

def get_name()
    while true
        print("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

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