[go: up one dir, main page]

0% found this document useful (0 votes)
57 views2 pages

Enumerable Cheat Sheet: "Candace" "Jon" "Jose"

This document provides a cheat sheet of enumerable methods in Ruby, including examples of using each, each_with_index, and each_char on arrays and strings, times to repeat a block, and specifying ranges using (start..end) or (start...end). It demonstrates iterating over elements of arrays and characters of strings, with or without indexes, as well as repeating a block a set number of times and generating ranges of numbers.

Uploaded by

Oksana Erm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views2 pages

Enumerable Cheat Sheet: "Candace" "Jon" "Jose"

This document provides a cheat sheet of enumerable methods in Ruby, including examples of using each, each_with_index, and each_char on arrays and strings, times to repeat a block, and specifying ranges using (start..end) or (start...end). It demonstrates iterating over elements of arrays and characters of strings, with or without indexes, as well as repeating a block a set number of times and generating ranges of numbers.

Uploaded by

Oksana Erm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

enumerable_cheat_sheet_reading.

md 12/12/2019

Enumerable Cheat Sheet

Here is a quick reference for the methods and operations we learned in the previous lectures!

Array Enumerable Methods

people = ["Candace", "Jon", "Jose"]

# iterate over elements of an array using each


people.each { |person| puts person } # prints
# Candace
# Jon
# Jose

# iterate over elements of an array with index using each_with_index


people.each_with_index do |person, i|
puts person
puts i
puts "-----"
end # prints
# Candace
# 0
# -----
# Jon
# 1
# -----
# Jose
# 2
# -----

String Enumerable methods

greeting = "hello"

# iterate over characters of a string using each_char


greeting.each_char { |char| puts char } # prints
# h
# e
# l
# l
# o

# iterate over characters of a string with index using


each_char.with_index
greeting.each_char.with_index do |char, i|
puts char
puts i
puts "---"
end # prints
1/2
enumerable_cheat_sheet_reading.md 12/12/2019

# h
# 0
# ---
# e
# 1
# ---
# l
# 2
# ---
# l
# 3
# ---
# o
# 4
# ---

Other

# repeat a block using times


3.times do
puts "hi"
end # prints
# hi
# hi
# hi

# specify a range of numbers using (start..end) or (start...end)

# including end
(2..6).each {|n| puts n} # prints
# 2
# 3
# 4
# 5
# 6

# excluding end
(2...6).each {|n| puts n} # prints
# 2
# 3
# 4
# 5

2/2

You might also like