7

When I find the keyword "in" in ruby first time. I think maybe I can do that: 1 in (0..10) But it look like I cannot use it like that way.

Then I search it in ruby-lang.org, and google it. There is no answer!

What's the meaning of keyword "in" in ruby?

colder
  • 644
  • 7
  • 12

3 Answers3

6

You should be able to do the following:

for i in 0..10 do
  puts i
end

The expression 1 in (0..10) that you mention won't work because a constant (1) can't vary over a range - it's a constant! You need to name a variable before the in keyword.

Hope that helps.

See this page as well.

Mark Pim
  • 9,898
  • 7
  • 40
  • 59
0

according to the pragmatic programmers book you se it as following

while *name*[, *name*]... in *expression* [do | :]
  body
end

so you use it in loops, sorry if this is vague, but i have only started learning ruby.

Craig
  • 1,199
  • 1
  • 13
  • 27
0

I think maybe I can do that: 1 in (0..10) But it look like I cannot use it like that way

Now you can :)

Because Ruby introduced pattern matching

1 in 0..10 is alias of this code:

case 1
in 0..10
  true
else
  false
end

Using 1 in 0..10 expression you can check if one expression matches another

mechnicov
  • 12,025
  • 4
  • 33
  • 56