Ruby/String/chomp

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

chomp and chomp!

s = "hello\r\n"      # A string with a line terminator
s.chomp!             # => "hello": remove one line terminator from end
s.chomp              # => "hello": no line terminator so no change
s.chomp!             # => nil: return of nil indicates no change made
s.chomp("o")         # => "hell": remove "o" from end
$/ = ";"             # Set global record separator $/ to semicolon
"hello;".chomp       # => "hello": now chomp removes semicolons and end



chomp! returns nil without altering the string because there is no record separator at the end of the string

joe = <<limerick
T
q
limerick
joe.chomp!
puts joe
joe.chomp!
puts joe
joe.chomp! # => nil
puts joe



The chomp and chop Methods

# The chop (or chop!) method chops off the last character of a string
# the chomp (chomp!) method chomps off the record separator ($/) 
joe = <<limerick
T
q
limerick
puts joe
# Apply chomp! to remove the last record separator (\n)
joe.chomp! 
puts joe