C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: The exclamation mark after tr means that tr will change the string in-place. We need to assign no variables.
Note: In the following examples, we refine our rot13 code, using a method and an abbreviated syntax for tr.
Ruby program that uses tr
# Input string.
value = "gandalf"
# Use tr to translate one alphabet to another.
value.tr!("abcdefghijklmnopqrstuvwxyz",
"nopqrstuvwxyzabcdefghijklm")
# Our result.
puts value
Output
tnaqnys
Tip: In Ruby, a return keyword is not always needed. A single-statement method will automatically treat the statement as a return value.
Ruby program that uses def, rot13 method
def rot13(value)
return value.tr("abcdefghijklmnopqrstuvwxyz",
"nopqrstuvwxyzabcdefghijklm")
end
# Use rot13 method.
puts rot13("gandalf")
puts rot13(rot13("gandalf"))
Output
tnaqnys
gandalf
And: This method will have fewer possible typos. It is easier to review for correctness.
Ruby program that uses character ranges, tr
def rot13(value)
return value.tr("a-z", "n-za-m")
end