Class: Rubic::LineGroup
- Inherits:
-
Object
- Object
- Rubic::LineGroup
- Defined in:
- lib/rubic.rb
Overview
Represents program (as a set of lines)
Instance Method Summary collapse
- #clear ⇒ Object
-
#initialize ⇒ LineGroup
constructor
A new instance of LineGroup.
- #lines ⇒ Object
- #load(file_name, with_line_numbers) ⇒ Object
- #resize(gap) ⇒ Object
- #save(file_name, with_line_numbers) ⇒ Object
- #stringify(with_line_numbers) ⇒ Object
- #update(line_num, expr) ⇒ Object
Constructor Details
#initialize ⇒ LineGroup
Returns a new instance of LineGroup.
16 17 18 |
# File 'lib/rubic.rb', line 16 def initialize @lines = {} end |
Instance Method Details
#clear ⇒ Object
24 25 26 |
# File 'lib/rubic.rb', line 24 def clear @lines = {} end |
#lines ⇒ Object
20 21 22 |
# File 'lib/rubic.rb', line 20 def lines @lines.sort_by { |line_num, _| line_num } end |
#load(file_name, with_line_numbers) ⇒ Object
64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/rubic.rb', line 64 def load(file_name, with_line_numbers) @lines = File.readlines(file_name, chomp: true) .each_with_index .map do |line, i| if with_line_numbers line_num, line = line.split(" ", 2) line_num = Integer(line_num) [line_num, line] else [i + 1, line] end end.to_h end |
#resize(gap) ⇒ Object
36 37 38 39 40 41 42 43 |
# File 'lib/rubic.rb', line 36 def resize(gap) @lines = @lines .sort_by { |line_num, _| line_num } .each_with_index .map { |hsh, i| [(i + 1) * gap, hsh[1]] } .to_h end |
#save(file_name, with_line_numbers) ⇒ Object
57 58 59 60 61 62 |
# File 'lib/rubic.rb', line 57 def save(file_name, with_line_numbers) File.open(file_name, "w") do |file| file.write(stringify(with_line_numbers)) file.write("\n") end end |
#stringify(with_line_numbers) ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/rubic.rb', line 45 def stringify(with_line_numbers) lines = @lines.map { |k, v| [k, v] } lines.sort_by { |k, _| k }.map do |line_num, line| if with_line_numbers "#{line_num} #{line}" else line end end.join("\n") end |
#update(line_num, expr) ⇒ Object
28 29 30 31 32 33 34 |
# File 'lib/rubic.rb', line 28 def update(line_num, expr) if expr.nil? @lines.delete(line_num) else @lines[line_num] = expr end end |