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

···

--
Posted via http://www.ruby-forum.com/.

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 Korrapati
http://vikhyat.net/

···

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

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

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

···

Il giorno Sun, 22 Jan 2012 05:46:00 +0900 josh smith <use_this_123@hotmail.com> ha scritto:

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

That is why the output is different.

Vikhyat Korrapati
http://vikhyat.net/

thanks :slight_smile:

···

--
Posted via http://www.ruby-forum.com/\.

I hope this helps

Stefano

It does. Thank alot!

···

--
Posted via http://www.ruby-forum.com/\.

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

···

On Sat, Jan 21, 2012 at 10:03 PM, josh smith <use_this_123@hotmail.com> wrote:

I hope this helps

Stefano

It does. Thank alot!

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/