Ruby: String Operations
Substring
Substring extraction is done by appending a bracket [index,count]
.
#-*- coding: utf-8 -*- # ruby # substring aa = "01234567" p aa[0,2] # prints “01”. Start with index, then count of chars. # negative index counts from end. -1 is last char. p aa[-2,2] # prints “67”.
String Length
Length of the string is .length
method.
# -*- coding: utf-8 -*- # ruby a="this" p a.length # 4
String Join and Repetition
Strings can be joined by a plus sign +
.
# -*- coding: utf-8 -*- # ruby p "this" + " that" # "this that"
String can be repeated using *
.
# -*- coding: utf-8 -*- # ruby print "this" * 2 # thisthis