DIfferent outputs?

Hi,

So im a newb to ruby. Just started learning today morning.
I tried the following two cases but can not figure out why the outputs
are different.

[“recycler”].include?(‘recycle’)

False

“recycler”.include?(‘recycle’)

True

Thank you

On Sunday 22 January 2012 at 2:16 AM, josh smith wrote:

“recycler”.include?(‘recycle’)

True

Hi,

The .include? method on an array and the one on a string have different
functions.

For an array, .include? will check whether any of the elements are equal
to the argument, while in a string it will check whether the argument is
a substring of the string.

That is why the output is different.

Vikhyat K.
http://vikhyat.net/

Il giorno Sun, 22 Jan 2012 05:46:00 +0900
josh smith [email protected] ha scritto:

“recycler”.include?(‘recycle’)

True

Thank you

The first line asks the array [“recycler”] whether it includes the
element
‘recicle’. This means that you’re calling the method Array#include? . If
you
look at its documentation, you’ll see that it returns true only if one
of the
elements of the array is equal as the argument. In your example, the
array
contains a single argument, “recycler”, which is different from the
argument
('recycle).

When calling “recycler”.include?(‘recycle’), instead, you’re calling the
method String#include?, which returns true if the string contains the
argument. Since the word “recycler” contains the word “recycle”, in your
example, it returns true.

I hope this helps

Stefano

That is why the output is different.

Vikhyat K.
http://vikhyat.net/

thanks :slight_smile:

I hope this helps

Stefano

It does. Thanks alot!

On Sat, Jan 21, 2012 at 10:03 PM, josh smith [email protected]
wrote:

I hope this helps

Stefano

It does. Thank alot!

Maybe you want to check whether there is any string which contains the
sequence “recycle”. Then you can do:

irb(main):003:0> [“recycler”].any? {|s| s.include?(“recycle”)}
=> true

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs