5

String.slice! produces a strange result

 3 years ago
source link: https://www.codesd.com/item/string-slice-produces-a-strange-result.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

String.slice! produces a strange result

advertisements

The following produces a strange result for slice! (unless I have made a mistake).

irb session with ruby 2.2.5p319 (2016-04-26 revision 54774) [x86_64-linux]

irb(main):001:0> a= File.read(',a');nil
=> nil
irb(main):002:0> a.class.name
=> "String"
irb(main):003:0> a.size
=> 66173
irb(main):004:0> b=a.slice(0..65534);nil
=> nil
irb(main):005:0> b.size
=> 65535
irb(main):006:0> a.slice!(0..65534);nil
=> nil
irb(main):007:0> a.size
=> 638
irb(main):008:0>

where file ",a" is a text string of length 66173 characters.

The string needs to be trimmed to fit a mysql column of type :text which has a max size of 65535 characters,

If the variable a is sliced to a new String variable b it results in a correct slice.

If the variable a is sliced in place, seems to do odd things resulting in a length of 638. Why?

Could someone explain what is going on?


slice!

Deletes the specified portion from str, and returns the portion deleted.

66173 - 65535
# => 638

tl;dr: a = slice!(...) is not equivalent to a = a.slice(...).


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK