1

I am currently experimenting with arrays in irb.

If my array has 22 elements, it will display properly as shown below: (Screenshot)

#Ruby Version 3.4.7
x = 1..22
#=> 1..22
x.to_a 
#=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 
# 22]

However, if my array has more than 22 elements, irb will render the array elements line by line:(Screenshot)

#Ruby Version 3.4.7
x = 1..23
#=> 1..23
x.to_a 
#=> 
# [1,
# 2,
# 3,
# 4,
# 5,
# 6,
# 7,
# 8,
# 9,
# 10,
# 11,
# 12,
# 13,
# 14,
# 15,
# 16,
# 17,
# 18,
# 19,
# 20,
# 21,
# 22,
# 23] 

May I know what is going on?

I tried use control c but my terminal will hang and I have to restart the terminal.

7
  • Please share more details, like the code involved Commented Oct 15 at 9:21
  • 1
    I’m voting to close this question because there’s not an actual error, it’s just a formatting difference. Commented Oct 15 at 9:49
  • 3
    irb's default output is wrapped based on available screen width, see lib/irb/color_printer.rb. You could switch to simple prompt via irb --simple-prompt. Commented Oct 15 at 10:38
  • @NicoHaase there's no code involved, the question is about a software tool. Commented Oct 15 at 10:41
  • 2
    @engineersmnky you took the time to transcribe the screenshots but then decided to close the question? :-) Commented Oct 16 at 16:27

1 Answer 1

3

IRB by default) prints objects by using the PrettyPrint resp. PP classes. They allow objects to specify how its inspect output is structured to while providing adaptive formatting based on available space in the console.

As such, the output is generally similar to that of inspect but is generated entirely differently.

For arrays, this is implemented as follows:

class Array
  # This method is called with a `PrettyPrint` object as its argument
  # in order to define the array's structure which is then printed
  # based on the available console space.
  def pretty_print(q)
    q.group(1, '[', ']') {
      q.seplist(self) {|v|
        q.pp v
      }
    }
  end

  # This method is called when printing object cycles, i.e.,
  # when an array contains itself. It also receives a `PrettyPrint`
  # object as its argument.
  def pretty_print_cycle(q)
    q.text(empty? ? '[]' : '[...]')
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.