Вопрос по ruby – Рубин для петли ловушка?

15

Error: User Rate Limit ExceededНиклас Б.Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded

Error: User Rate Limit ExceededforError: User Rate Limit Exceededdo/endError: User Rate Limit ExceededselectError: User Rate Limit ExceededmapError: User Rate Limit Exceeded Niklas B.
Error: User Rate Limit Exceeded Niklas B.
Error: User Rate Limit ExceededwantError: User Rate Limit Exceeded Boris Stitnicky
Error: User Rate Limit ExceededforError: User Rate Limit Exceededstackoverflow.com/questions/3294509/for-vs-each-in-ruby Niklas B.

Ваш Ответ

3   ответа
14

results = []
(1..3).each do |i|
  results << lambda { i }
end
p results.map(&:call)  # => [1,2,3]

results = []
for i in 1..3
  results << lambda { i }
end
p results.map(&:call)  # => [3,3,3]

EnumerableforEnumerable#each

lambdas = 1.upto(3).map { |i| lambda { i } }
p lambdas.map(&:call)

I expand the question: Where else in Ruby do we see what apears do/end block delimiters, but there is actually no scope inside? Anything else apart from for ... do ... end?

while true do
  #...
end

until false do
  # ...
end

do

for i in 1..3
end

while true
end

until false
end

One more expansion of the question, is there a way to write for loop with curly braces { block }

Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededneverError: User Rate Limit ExceededforError: User Rate Limit ExceededEnumerableError: User Rate Limit Exceeded
Error: User Rate Limit ExceededforError: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded Boris Stitnicky
1

i = 0
results = []
(1..3).each do |i|
  results << lambda { i }
end
i = 5
p results.map(&:call)  # => [5,5,5]
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit ExceededscopeError: User Rate Limit ExceededscopeError: User Rate Limit ExceededvariablesError: User Rate Limit ExceededvaluesError: User Rate Limit ExceedediError: User Rate Limit ExceededcalledError: User Rate Limit Exceededdefined.
Error: User Rate Limit Exceeded[1,2,3]Error: User Rate Limit Exceeded
2

for

foreacheachmapfindeach_with_indexfor_mapfor_findfor_with_index.

each

for. eachwhile

RUN_COUNT = 10_000_000
FIRST_STRING = "Woooooha"
SECOND_STRING = "Woooooha"

def times_double_equal_sign
  RUN_COUNT.times do |i|
    FIRST_STRING == SECOND_STRING
  end
end

def loop_double_equal_sign
  i = 0
  while i < RUN_COUNT
    FIRST_STRING == SECOND_STRING
    i += 1
  end
end

times_double_equal_signloop_double_equal_sign

forfor

Похожие вопросы