Search
 
SCRIPT & CODE EXAMPLE
 

RUBY

meaning of {} in ruby

This is probably the most tricky one - {} is also syntax for blocks, but only when passed to a method OUTSIDE the arguments parens.

When you invoke methods without parens, Ruby looks at where you put the commas to figure out where the arguments end (where the parens would have been, had you typed them)

1.upto(2) { puts 'hello' } # it's a block
1.upto 2 { puts 'hello' } # syntax error, ruby can't figure out where the function args end
1.upto 2, { puts 'hello' } # the comma means "argument", so ruby sees it as a hash - this won't work because puts 'hello' isn't a valid hash
Comment

meaning of {} in ruby

When on their own, or assigning to a variable, [] creates arrays, and {} creates hashes. e.g.

a = [1,2,3] # an array
b = {1 => 2} # a hash
[] can be overridden as a custom method, and is generally used to fetch things from hashes (the standard library sets up [] as a method on hashes which is the same as fetch)
a = {1 => 2} # create a hash for example
puts a[1] # same as a.fetch(1), will print 2
Comment

PREVIOUS NEXT
Code Example
Ruby :: rails helper in controller 
Ruby :: create_enum in rails 7 
Ruby :: rails keep all params except for some 
Ruby :: ruby merge array of hashes into one hash 
Ruby :: read headers of csv using ruby 
Ruby :: ruby append to array 
Ruby :: ruby routes 
Ruby :: ruby array shift 
Ruby :: selenium webdriver get attribute ruby 
Ruby :: While executing gem 
Ruby :: select tag . Default value rails 
Ruby :: manage ruby versions 
Ruby :: list objects of a class ruby 
Ruby :: ruby convert value to boolean 
Ruby :: List columns in table from console 
Ruby :: ruby simbolize element from hash 
Ruby :: EOFError: end of file reached 
Ruby :: devise signout via get with https 
Ruby :: ruby on rails recover data in params with form tag 
Ruby :: rails include dynamic 
Ruby :: how to group array in ruby 
Ruby :: comment 
Ruby :: how to use custom switch in rails 
R :: how to create dates in a range in R 
R :: find data types in list r 
R :: r convert matrix to list of column vectors 
R :: write to csv in r 
R :: r - transform as factor 
R :: r replace na with 0 
R :: convert first row to header in r 
ADD CONTENT
Topic
Content
Source link
Name
7+7 =