Skip to content

Commit e587257

Browse files
authored
Merge pull request #67 from jvelez1/ruby/_with_lambdas
Ruby with lambdas
2 parents 57a6dc6 + 61d544e commit e587257

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

ruby/with_lambdas.rb

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
require 'json'
2+
3+
sections = [
4+
{
5+
"title": "Getting started",
6+
"reset_lesson_position": false,
7+
"lessons": [
8+
{"name": "Welcome"},
9+
{"name": "Installation"}
10+
]
11+
},
12+
13+
{
14+
"title": "Basic operator",
15+
"reset_lesson_position": false,
16+
"lessons": [
17+
{"name": "Addition / Subtraction"},
18+
{"name": "Multiplication / Division"}
19+
]
20+
},
21+
22+
{
23+
"title": "Advanced topics",
24+
"reset_lesson_position": true,
25+
"lessons": [
26+
{"name": "Mutability"},
27+
{"name": "Immutability"}
28+
]
29+
}
30+
]
31+
32+
reset_lesson_position = lambda {|lessons| lessons.each.with_index(1) { |lesson, index| lesson.merge!(position: index) } }
33+
34+
modify_section = lambda do |section, indexed_lessons|
35+
lessons = section[:reset_lesson_position] ? reset_lesson_position.call(section[:lessons]) : indexed_lessons
36+
section.merge!(lessons: lessons)
37+
end
38+
39+
indexed_sections = sections.flat_map{ _1[:lessons] }.each.with_index(1) { |a, index| a.merge!(position: index) }
40+
sections.map { |section| modify_section.call(section, indexed_sections.shift(section[:lessons].count)) }
41+
42+
puts JSON.pretty_generate(sections)

0 commit comments

Comments
 (0)