DEV Community

es404020
es404020

Posted on

Working with Strings in Ruby(Part 1)

Understanding Strings in ruby

The following are used to display a variable in ruby
puts ,p and prints

The main distinction is that "puts" create a new line after showing the variable content while "print" doesn't.

Note: Single cot and double quote can be both used for string, but single quote doesn't not support string interpolation.

1.String concatenation

firstname=  "solomon"
lastname ="ajani"
puts firstname + "" + lastname


Enter fullscreen mode Exit fullscreen mode

2.String interpolation

we use #{} to access variable in a string in ruby


 puts "my surname is #{last} and my first name is #{firstname}"

Enter fullscreen mode Exit fullscreen mode

3.Method on string

To check the type on a variable you can do the following .In Ruby everything is an object.

firstname.class
#output= String

"hello world".class
#output = String


10.class
#output  = Integer

Enter fullscreen mode Exit fullscreen mode

To get built in methods in string simple type

"hello world".methods

Enter fullscreen mode Exit fullscreen mode


`

Some String methods

to_s: Converts integer to string

length: Get the length of a string

reverse: reverse an array or string

capitalize: Make the first letter capitalize

sub: To replace a world in a string

`
sentence ="Our President is a good boy"
sentence.sub("good boy","bad boy")

`

Difference between sub and gsub is gsub replaces all occurrence of a specified variable

4.Escape in String

Take for instance we want this display this

"Doe'nt" this would keep throwing an error.

to fix use

puts "Doe\'nt"

\ sign help escape the string

Thanks for reading.

Top comments (0)