Introduction
String slicing and indexing let you pick out parts or single characters from a string, like cutting a piece from a loaf of bread.
string[index]
string[start, length]
string[range]name = "Ruby" puts name[0] # R puts name[-1] # y
text = "Hello World" puts text[0, 5] # Hello
phrase = "Good morning" puts phrase[5..11] # morning
sentence = "Programming is fun" first_char = sentence[0] last_char = sentence[-1] word = sentence[0, 11] puts "First character: #{first_char}" puts "Last character: #{last_char}" puts "First word: #{word}"
str[0] return when str = "hello"?str[0] returns the first character 'h'.str = "hello" using slicing?str[start, length] extracts a substring starting at start with length characters.str[1,3] returns 'ell'.str = "programming" puts str[-4, 3]
str = "example" puts str[2..5, 2]
str[2..5, 2] which mixes range and length parameters incorrectly. Ruby does not support this syntax.str[2..5] for range or str[2, 2] for start and length. Mixing both causes a syntax error.str = "abracadabra", which code extracts every second character starting from index 0 to index 8 (inclusive)?str[0, 8, 2] or str[0..8][::2] are invalid.str[0..8] gets substring 'abracadab'. Then chars.select.with_index { |_, i| i.even? } picks characters at even indices: a (0), r (2), c (4), d (6), b (8). Joining gives 'ar cdb' without spaces: 'arcdb'.Pass the test and this pattern moves unknown