-2

What does [] mean when it is next to an iterative function. Not entailing keys and values e.g. { |char| count[char] += 1 }

  • What do you mean by _next to an iterative function_? What is an _iterative function_ anyway? The brackets are next to the word `count` in your example. Without knowing the context, `count` can be a function or a variable. If it is a function, it is one which returns as value an object, which understands `[]`(which is nothing special; just a method call). For instance, objects of class `Array` or `Hash` understand `[]`, but you can also write your own class which understands it. Hence, without knowing more of your program, your question can not be answered. – user1934428 Jul 14 '20 at 14:49

3 Answers3

0

Some Parts of Block Syntax Explained

{ |char| count[char] += 1 } is a block. If you're new to Ruby, it may help to think of a block as a sort of anonymous function, but it's actually a language feature that's distinct from Proc and lambda objects. All methods in Ruby implicitly accept a block as their final argument, whether or not they use it.

Inside the block, |char| declares the variable that will hold the values passed into the block. Various language features that yield values to blocks will pass their values to the variables so declared.

count[char] is just a Hash or Array lookup. It retrieves the value in count associated with the key or index in char. In your specific example, the value at count[char] needs to be an Integer, or the expression will probably raise a TypeError exception.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
0

TL;DR: obj[...] calls the method [] on obj (with arguments ...)


Your code snippet is probably used to count char occurrences in a string:

str = 'hello world'
count = Hash.new(0)
str.each_char { |char| count[char] += 1 }

count
#=> {"h"=>1, "e"=>1, "l"=>3, "o"=>2, " "=>1, "w"=>1, "r"=>1, "d"=>1}

Here, count is a hash with a default value of 0.

Within the block, char is one of the string's character, i.e. "h", "e", "l" etc.

The brackets are syntactic sugar for a method call: Hash#[] (element reference). But there's another, hidden method call. In Ruby, a += b is syntactic sugar for a = a + b. So count[char] += 1 is actually:

count[char] = count[char] + 1

The left-hand-side being Hash#[]= (element assignment).

Stefan
  • 109,145
  • 14
  • 143
  • 218
-1

[ ] are used to access positions within an array or keys within a hash. in this case you are entering the position char or the corresponding key in this iteration

#example
my_array = ['hola', 'chao', 'brb']
my_array[0] #show "hola"

3.times {|x| p my_array[x]} 
#"hola"
#"chao"
#"brb"
#=> 3