Nelly-Johan Nelly-Johan - 2 months ago 6
Ruby Question

Extract charcarters from a string

I am trying to create an little program where people could transform their name with chemical symbols (The Breaking bad way's).

I can get the two first letters, but I don't know how to get separately the rest of the letters:

puts "Please enter your name"
name = gets.chomp
first_letters = name[0,1]
last_letters = name - first_letters #I know it's wrong but here is the idea of what i want to do. Hope it's clear...


And then I will display the name with images corresponding to the first letters.

if first_letters.include? "br"
puts "Br" + last_letters
end
if first_letters.include? "ba"
puts "Ba" + last_letters
end


How can I isolate the last letters?

Thanks

Answer

You are almost there:

name[2..-1]

or

name[2..name.length]

or if you want to go the regular expression way (no real need for that much complexity here)

match = name.match(/(.{2})(.*)/)
first_letters = match[1]
last_letters = match[2]

Now in all variants you might want to add some checking that the name has sufficient length.