K
K
krlljs2014-09-26 01:52:08
ruby
krlljs, 2014-09-26 01:52:08

Reverse engineering: Computing the initial algorithm of a Ruby program. What does the code written starting on the third line mean?

There is a task:

Дана последовательность:

1
11
21
1211
111221
312211

Нужно чтобы ваша программа могла продолжить данную последовательность.
Можете в реализации использовать любые библиотеки.
There is a solution:
value = '1'
puts value
10.times do
  next_value = value.chars.inject([]) do |arr, next_char|
    if !arr.empty? && arr.last.has_key?(next_char)
      arr.last[next_char] += 1
    else
      arr << {next_char => 1}
    end
    arr
  end
  value = ''
  next_value.map do |hash| 
    hash.each_pair{ |k,v| value << "#{v}#{k}" }
  end
  puts value
end

But this solution suits me, because. it's from the web. So I'm trying to develop my own. Therefore, I want to see the algorithm from the solution found on the net.
There is something that is not clear to me in the solution, for example:
10.times do
What does 10.times mean ? What does do mean ?
Or:
arr << {next_char => 1}
What does double less mean ? What does {next_char => 1} mean?
It’s not that the syntax is not clear, it’s just that little is clear so far, my eyes run wide:
next_value = value.chars.inject([]) do |arr, next_char|
    if !arr.empty? && arr.last.has_key?(next_char)
      arr.last[next_char] += 1
    else
      arr << {next_char => 1}
    end
    arr
From all this, I saw only the do-end and if-else construction , nothing else. I will say right away that I am not a ruby ​​developer, but I want to become one.
The only thing I understand is the first two lines:
value = '1'
puts value

On the first line, the value variable is created. On the second, it is interpolated.
If any of you comment on this solution line by line, it will help me a lot.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Filippov, 2014-09-26
@krlljs

If you want to become a Ruby developer, you should read about the language itself and the main constructs.
One gets the feeling that you have 0 with English and with programming as well. Take time for theory to get started.
After these lines, I realized that you are trolling:


On the first line, the value variable is created. On the second, it is interpolated.

I confess, I began to answer questions without reading up to this insanity.

P
Philipp, 2014-09-26
@zoonman

The first thing to remember is that almost all data in Ruby is an object.
Hence the conclusion that times is a method. Looking for continuation here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question