Skip to content
jschanker edited this page Feb 16, 2016 · 1 revision

Text

The code fragments below assume that string_variable was previously set according to Variables. E.g.,

set string_variable to "abcdefgdef"

If one of these phrases doesn't seem to work in a larger expression or statement, try surrounding the entire code phrase with parentheses.

Length of string

string-functions-length

length of string_variable

This works even if string_variable is replaced with a string literal such as "abcdefgdef" or a string variable set in the usual Ruby way (e.g., string_variable = "abcdefgdef")

Find position of first/last occurrence of substring

string-functions-find-first

from text string_variable find first occurrence of text "abc"
  • Replacing first with last gives you the last occurrence of the text.
  • If the string isn't found, the expression returns nil instead of a number as is the case with Ruby's index/rindex String methods.
  • Indices go from 1 to the length of string_variable (instead of 0 to length-1) so the above would result in 1 instead of 0.
  • "abc" can be replaced with a string variable, say substring_variable, that was set using the usual substring_variable = "abc" or Set substring_variable to "abc" statements.
  • string_variable can be replaced with a string literal provided that find is preceded by a . instead of a space as follows:
from text "abcdefgdef".find first occurrence of text "abc"

Get letter at position in string

string-functions-get-letter

from text string_variable get letter 1
  • Indices go from 1 to the length of string_variable (instead of 0 to length-1) so the above would result in a instead of b.
  • 1 can be replaced with a variable storing an integer.
  • To use a string literal or string_variable set in the usual Ruby way, change the space preceding get to a . as follows:
from text "abcdefgdef".get letter 1

Get substring of string

string-functions-substring

from text str get substring from letter start, end
  • Indices go from 1 to the length of string_variable (instead of 0 to length-1).
  • start and end can be any variables storing integers and can be replaced with integer literals.
  • To use a string literal or string_variable set in the usual Ruby way, change the space preceding get to a . as follows:
from text "abcdefgdef".get substring from letter start, end

Input

string-functions-prompt-for-text

prompt to get text with message "Enter something interesting:"

text can be replaced with number to attempt to convert the entered expression into a decimal number. The function is implemented by returning gets.chomp or the result of applying .to_f in the case that text is replaced with number.

Clone this wiki locally