Crystal: Fetch a char from string to equal the same string(char) return false

Created on 29 Jun 2017  路  12Comments  路  Source: crystal-lang/crystal

icr(0.22.0) > "hello!"[-1] == "!"
 => false
icr(0.22.0) > "==="[0] == "="
 => false
icr(0.22.0) > "==="[0].to_s == "="
 => true
icr(0.22.0) > "==="[0] == "=".chars[0]
 => true

2.4.1 :001 > "hello!"[-1] == "!"
 => true
2.4.1 :002 > "==="[0] == "="
 => true

Is this logic correct?

All 12 comments

Yes, Char will never be equal to String.

https://play.crystal-lang.org/#/r/29tu

But You can override this behavior with:

https://play.crystal-lang.org/#/r/29ty

Reminder that overriding such behaviour globally is likely to break other shards or the stdlib. If you want to compare a character use Char.

@RX14 I suppose that's related to Frameworks. Rails actively override core things and it's OK.

IMHO, Crystal like a Ruby just the foundation for frameworks like Rails.

@akzhan and rails breaks things. From what I've heard it's not even rare.

@RX14 Crystal follows Ruby idea to metaprogramming. And it's great.

And yes, I dislike some defaults of Crystal (like String.underscore behavior), So ability to fix it for own code is beautiful.

It will inevitably lead to problems with 3rd party code. If you're only using your own code, that's okay. But when you rely on 3rd party shards, I wouldn't change behavior of stdlib.

@straight-shoota Yes, it is. But Crystal is foundation. A lot of people will use higher level frameworks.

P.S.: I'm used Rack not Rails. And Rails is great concept built extending and overriding Ruby.

Rails has such an important status in the Ruby ecosystem that 3rd party libraries just have to deal with the monkey patches from rails, because they are everywhere ;)

thanks @akzhan. Maybe It's better to update this behavior to document. 馃槃

Update this benchmark to fast-crystal#equal-substring-of-char-code

$ crystal build --release code/string/equal-substring-of-char.cr -o bin/string/equal-substring-of-char
$ ./bin/string/equal-substring-of-char

Crystal 0.22.0 (2017-04-22) LLVM 4.0.0
         "==="[0] == '=' 252.73M (  3.96ns) (卤12.75%)       fastest
    "==="[0].to_s == "="  19.65M ( 50.88ns) (卤 2.72%) 12.86脳 slower
"==="[0] == "=".chars[0]  16.97M ( 58.91ns) (卤 3.48%) 14.89脳 slower

Thanks @icyleaf.

btw, take a look at #4586. Looks like we need tests for gsub vs tr.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

farleyknight picture farleyknight  路  64Comments

chocolateboy picture chocolateboy  路  87Comments

xtagon picture xtagon  路  132Comments

asterite picture asterite  路  71Comments

malte-v picture malte-v  路  77Comments