Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BitArray.to_s should output the same format as Int.to_s #10364

Open
dukeraphaelng opened this issue Feb 5, 2021 · 2 comments
Open

BitArray.to_s should output the same format as Int.to_s #10364

dukeraphaelng opened this issue Feb 5, 2021 · 2 comments

Comments

@dukeraphaelng
Copy link
Contributor

dukeraphaelng commented Feb 5, 2021

Currently BitArray.to_s is outputting in the format BitArray[00000]

crystal/src/bit_array.cr

Lines 212 to 226 in f0901e1

# Creates a string representation of self.
#
# ```
# require "bit_array"
#
# ba = BitArray.new(5)
# ba.to_s # => "BitArray[00000]"
# ```
def to_s(io : IO) : Nil
io << "BitArray["
each do |value|
io << (value ? '1' : '0')
end
io << ']'
end

It would be more convenient and make more sense to have the output format similar to Int.to_s - so that it can be converted from a base 2 digit into a number of a different base, i.e.

 def to_s(io : IO) : Nil 
   each do |value| 
     io << (value ? '1' : '0') 
   end 
 end 

If we want the string representation explicitly stated in the string, then we can use .inspect (keep the current implementation):

  def inspect(io : IO) : Nil
    io << "BitArray["
    to_s(io)
    io << ']'
  end
@asterite
Copy link
Member

asterite commented Feb 5, 2021

Even though I think it's a good idea to have a way to format it like that, I don't think the default should be that. If you see "1001" in the output of "to_s" you might think it's a number, when it's not.

@straight-shoota
Copy link
Member

straight-shoota commented Feb 5, 2021

Providing an unambiguous representation is #inspect's job. #to_s is supposed to provide a natural representation. A series of 1 and 0 seems like a very natural representation to me. I'm not sure if that's definitely better for to_s, though. I don't think this type is used often for direct user presentation.
So maybe it could help if you could tell a bit about your use case, @dukeraphaelng?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants