Ruby Coding Lecture: Split, Join, Each, and Map Methods

1
508

In this lecture I take a deep dive and walk the devCamp code students through how to use the Ruby methods:

  • Split
  • Join
  • Each
  • Map

The code for the lecture is below:

Split

str = "Star Wars, Luke, Darth, Yoda"

p str.class
p str.split(/, /).count
["Star Wars", "Luke", "Darth", "Yoda"]
p str.split(/, /, 2).count
["Star Wars", "Luke, Darth, Yoda"]

first, *rest = str.split(/, /)
p first
p rest

api = "@=>Posts={title: asdfasdf, title: zxcvzxcv}, @=>Comments={body: qwe, body: vcxfgsfd}"
p api.split(/@=>/)
["", "Posts={title: asdfasdf, title: zxcvzxcv}, ", "Comments={body: qwe, body: vcxfgsfd}"]

Join

arr = ["Star Wars", "Luke", "Darth", "Yoda"]
p arr.join(', ')

arr = ["Star Wars", "Luke", "Darth", "Yoda"]

def sentence_join array
  array[0..-2].join(", ") + ", and " + array.last
end

p sentence_join arr

my_word = "Hello" # "olleH"

class String
  def alt_reverse
    str_array = self.split(//)
    reversed_array = []
    total_count = str_array.count
    total_count.downto(1) { |i| reversed_array << str_array[i - 1] }
    reversed_array.join
  end
end

p "asdfasdf".alt_reverse
# fdsafdsa

p "asdfasdf".chars.reduce { |a, b| b + a }
# fdsafdsa

Map

projects = ["TypeScript", "IDE", "Ruby Gem", "Angular"]

def styled_projects_with_each projects
    uppercase_projects = []
    projects.each do |project|
        uppercase_projects << project.upcase
    end
    uppercase_projects
end

def styled_projects_with_map projects
    projects.map(&:upcase)
end

p styled_projects_with_each projects
p projects.map(&:upcase)

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here