RosettaCodeData/Task/Binary-strings/Ruby/binary-strings.rb

48 lines
645 B
Ruby
Raw Permalink Normal View History

2013-04-10 12:38:42 -07:00
# string creation
x = "hello world"
# string destruction
x = nil
# string assignment with a null byte
x = "a\0b"
x.length # ==> 3
# string comparison
if x == "hello"
2013-10-27 22:24:23 +00:00
puts "equal"
2013-04-10 12:38:42 -07:00
else
puts "not equal"
end
y = 'bc'
if x < y
puts "#{x} is lexicographically less than #{y}"
end
# string cloning
xx = x.dup
x == xx # true, same length and content
x.equal?(xx) # false, different objects
# check if empty
if x.empty?
puts "is empty"
end
# append a byte
2013-10-27 22:24:23 +00:00
p x << "\07"
2013-04-10 12:38:42 -07:00
# substring
2013-10-27 22:24:23 +00:00
p xx = x[0..-2]
x[1,2] = "XYZ"
p x
2013-04-10 12:38:42 -07:00
# replace bytes
2013-10-27 22:24:23 +00:00
p y = "hello world".tr("l", "L")
2013-04-10 12:38:42 -07:00
# join strings
a = "hel"
b = "lo w"
c = "orld"
2013-10-27 22:24:23 +00:00
p d = a + b + c