In: Computer Science
Using Ruby. Create a program that prompt the users for his full name
For example: Brian Smith
You code should swap the first name to last and last name to first and display the result.
Smith Brian
Your code should run for any combination of first name and last name.
Hint: Research around String class methods in Ruby. The separator is the space in between first and last name.
Please submit your code, as well as screenshot of how your code ran in the console.
Code:
print "Enter your Full Name : " #asking user to enter the full Name
$full_name=STDIN.gets #taking user full name as input from user
$full_name=$full_name.strip #used for removing \n after entering name hitting enter takes \n as character
$final_name=$full_name.split(" ") #split the given name by using delimiter " "
puts $final_name[1] + " " + $final_name[0] #concatenate first index value with zeroth index value
Code and Outputs Screenshots:
Note: In program we are using strip function. the main operation of strip function is removing trailing spaces or tabs or new lines as well as ending spaces and tabs and new lines.Here in this program after entering the input we are hitting Enter button so the enter button (\n) is considering as input character and stores that into $full_name variable.
Here we are removing that last \n using strip function.
Note : if you have any queries please post a comment thanks a lot..always available to help you...