Ruby – Arrays

Create an array:

1. x = [1, 2, 3, 4]
puts x[2]
output:

3

2. x[2] += 1
puts x[2]

output:

4
3. x = []
x << “Word”
x << “Play”
x << “Fun”
puts x.pop
puts x.pop
puts x.length
output:

Fun
Play
1

4. x = [“Word”, “Play”, “Fun”]
puts x.join

output: WordPlayFun

5. x = [“Word”, “Play”, “Fun”]
puts x.join(‘, ‘)

output: Word, Play, Fun

Splitting Strings into Arrays:

1. puts “This is a test”.scan(/\w/).join(‘,’)

output:

T,h,i,s,i,s,a,t,e,s,t

2. puts “Short sentence. Another. No more.”.split(/\./).inspect

output: [“Short sentence”, ” Another”, ” No more”]

3. [1, “test”, 2, 3, 4].each { |element| puts element.to_s + “X” }

output:

1X
testX
2X
3X
4X

4. a = [1, “test”, 2, 3, 4]
i = 0
while (i < a.length)
puts a[i].to_s + “X”
i += 1
end

output:

1X
testX
2X
3X
4X

Array Subtraction and Difference

x = [1, 2, 3, 4, 5]
y = [1, 2, 3]
z = x – y
puts z.inspect
output: [4,5]

Check for an Empty Array

x = []
puts “x is empty” if x.empty?
output: x is empty

Check an Array for a Certain Item

x = [1, 2, 3]
puts x.include?(“x”)
puts x.include?(3)
output:

false
true

Access the First and Last Elements of the Array

1. x = [1, 2, 3]
puts x.first
puts x.last
output:

1
3

2. x = [1, 2, 3]
puts x.first(2).join(“-“)

output: 1-2

Reverse the Order of the Array’s Elements

x = [1, 2, 3]
puts x.reverse.inspect
output: [3, 2, 1]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s