get the first 3 characters and last 5 characters in a string then combine into a new string in ruby

To get the first three characters of a string, we can use Ruby's slice method with a range of 0..2, which would extract the characters at positions 0, 1, and 2:

main.rb
str = "example string"
first_three = str.slice(0..2)
puts first_three # "exa"
78 chars
4 lines

To get the last five characters of a string, we can use negative indexing to count from the end of the string. We can use slice again, this time with a range of -5..-1:

main.rb
last_five = str.slice(-5..-1)
puts last_five # "tring"
55 chars
3 lines

Finally, we can concatenate the two substrings using the + operator:

main.rb
new_str = first_three + last_five
puts new_str # "exatring"
60 chars
3 lines

We can also use string interpolation to accomplish the same thing:

main.rb
new_str = "#{first_three}#{last_five}"
puts new_str # "exatring"
65 chars
3 lines

gistlibby LogSnag