What Is $_[0] ,$_[1] in Ruby

What is [0] and [1..-1] in Ruby?

string[0] is a new string that contains the first character of string.

It is, in fact, syntactic sugar for string.[](0), i.e. calling the method String#[] on the String object stored in the variable string with argument 0.

The String#[] method also accepts a Range as argument, to extract a substring. In this case, the lower bound of range is the index where the substring starts and the upper bound is the index where the substring ends. Positive values count the characters from the beginning of the string (starting with 0), negative values count the characters from the end of the string (-1 denotes the last character).

The call string[1..-1] (string.[](1..-1)) returns a new string that is initialized with the substring of string that starts with the second character of string (1) and ends with its last character.

Put together, string[0].upcase is the uppercase version of the first character of string, string[1..-1] is the rest of string (everything but the first character).

Read more about different ways to access individual characters and substrings in strings using String#[] method.

What is $_[0] ,$_[1] in Ruby?

It's one of the magic variables.

$_ holds value of the last line read from standard input. $_[0] is, therefore, first symbol of that string.

See English.rb for more magic variables

# The last line read by <tt>Kernel.gets</tt> or
# <tt>Kernel.readline</tt>. Many string-related functions in the
# +Kernel+ module operate on <tt>$_</tt> by default. The variable is
# local to the current scope. Thread local.
alias $LAST_READ_LINE $_

each_with_index_do starting at 1 for index

I think maybe you misunderstand each_with_index.

each will iterate over elements in an array

[:a, :b, :c].each do |object|
puts object
end

which outputs;

:a
:b
:c

each_with_index iterates over the elements, and also passes in the index (starting from zero)

[:a, :b, :c].each_with_index do |object, index|
puts "#{object} at index #{index}"
end

which outputs

:a at index 0
:b at index 1
:c at index 2

if you want it 1-indexed then just add 1.

[:a, :b, :c].each_with_index do |object, index|
indexplusone = index + 1
puts "#{object} at index #{indexplusone}"
end

which outputs

:a at index 1
:b at index 2
:c at index 3

if you want to iterate over a subset of an array, then just choose the subset, then iterate over it

without_first_element = array[1..-1]

without_first_element.each do |object|
...
end

ruby why 0 || 1 is 0

Ruby only evaluates as much as it needs to in an expression like this and then stops, what you are seeing returned is just the last part of the expression that it evaluated.
So for your && case, it always has to run right to the end in case a later clause returns false and which would cause the AND to be false.

And actually your example is wrong:

irb> 0 && 1
=> 1

Which is expected since 0 is truthy in Ruby, not as false like in C.

For the OR case, it can stop as soon as it hits anything that is truthy and doesn't need to bother with the rest.

0 || false      # => 0
false || 0 # => 0
false || 0 || 2 # => 0

If you want to force an expression like this to a boolean this is how you often see it done:

!!(expression)
!!(0 || 1) => true
!!(nil || false) => false

Failure: Expected 0 to be = 1 on ruby on rails

The issue is that there is no html matching "Help | Ruby on Rails Tutorial Sample App".

if you look at the definition of assert_select, it accepts :count as (optional) argument. If the count is not specified, it sets the minimum occurrence of the html to 1. This is why the error you are getting is Expected 0 to be >= 1.. In your case there were 0 matches where the test expected at least 1 match.

Why 3[0] and 3[1] results in 1 in Ruby?

From the docs for Integer#[]:

Bit Reference---Returns the nth bit in the binary representation of int, where int[0] is the least significant bit.

3 is 11 in binary, so 3[0] (the least significant one) and 3[1] are 1 and everything else is 0.

Why do we have 0.0 and -0.0 in Ruby?

You can assign a negative sign to a 0.0 float in Ruby because all IEEE 754 floating point numbers have a sign bit to indicate whether the number is positive or negative.

Here are the binary representations of 2.5 and -2.5:

[2.5].pack('f').unpack1('b*')
#=> "00000000000000000000010000000010"

[-2.5].pack('f').unpack1('b*')
#=> "00000000000000000000010000000011"

The last bit is the sign bit. Note that all the other bits are identical.

On the other hand, there is zero with a sign bit of 0:

['00000000000000000000000000000000'].pack('b*').unpack1('f')
#=> 0.0

and zero with a sign bit of 1:

['00000000000000000000000000000001'].pack('b*').unpack1('f')
#=> -0.0

Although 0.0 and -0.0 are numerically equal, they are not identical on the object level:

(0.0).eql?(-0.0)   #=> true
(0.0).equal?(-0.0) #=> false

Negative zeros have some special properties.
For instance:

1 / 0.0    #=> Infinity
1 / -0.0 #=> -Infinity

Assigning - explicitly is not the only way to get -0.0. You may also get -0.0 as the result of a basic arithmetic operation:

-1.0 * 0 #=> -0.0

Ruby: Idiom for create and increment

The question is clear:

  • A variable is known to hold nil or an integer. If nil the variable is to be set equal to 1, else it is to be set equal to its value plus 1.
  • What is the best way to implement this in Ruby?

First, two points.

  • The question states, "If it is nil, it should be initialized with 1.". This contradicts the statement that the variable is known to be nil or an integer, meaning that it has already been initialized, or more accurately, defined. In the case of an instance variable, this distinction is irrelevant as Ruby initializes undefined instance variables to nil when they are referenced as rvalues. It's an important distinction for local variables, however, as an exception is raised when an undefined local variable is referenced as an rvalue.
  • The comments largely address situations where the variable holds an object other than nil or an integer. They are therefore irrelevant. If the OP wishes to broaden the question to allow the variable to hold objects other than nil or an integer (an array or hash, for example), a separate question should be asked.

What criteria should be used in deciding what code is best? Of the various possibilities that have been mentioned, I do not see important differences in efficiency. Assuming that to be the case, or that relative efficiency is not important in the application, we are left with readability (and by extension, maintainability) as the sole criterion. If x equals nil or an integer, or is an undefined instance variable, perhaps the clearest code is the following:

x = 0 if x.nil?
x += 1

or

x = x.nil? ? 1 : x+1

Ever-so-slightly less readable:

x = (x || 0) + 1

and one step behind that:

x = x.to_i + 1

which requires the reader to know that nil.to_i #=> 0.

The OP may regard these solutions as "clumsy", but I think they are all beautiful.

Can an expression be written that references x but once? I can't think of a way and one has not been suggested in the comments, so if there is a way (doubtful, I believe) it probably would not meet the test for readability.

Consider now the case where the local variable x may not have been defined. In that case we might write:

x = (defined?(x) ? (x || 0) : 0) + 1

defined? is a Ruby keyword.

What does ||= (or-equals) mean in Ruby?

This question has been discussed so often on the Ruby mailing-lists and Ruby blogs that there are now even threads on the Ruby mailing-list whose only purpose is to collect links to all the other threads on the Ruby mailing-list that discuss this issue.

Here's one: The definitive list of ||= (OR Equal) threads and pages

If you really want to know what is going on, take a look at Section 11.4.2.3 "Abbreviated assignments" of the Ruby Language Draft Specification.

As a first approximation,

a ||= b

is equivalent to

a || a = b

and not equivalent to

a = a || b

However, that is only a first approximation, especially if a is undefined. The semantics also differ depending on whether it is a simple variable assignment, a method assignment or an indexing assignment:

a    ||= b
a.c ||= b
a[c] ||= b

are all treated differently.



Related Topics



Leave a reply



Submit