Can't understand the behaviour of .to_i

Hi,
Just started learning programming with Ruby. Have been playing with the
following bits:

puts ‘4 is ok’.to_i + 2 gives the output 6

but

puts ‘4 is ok’.to_i +2 gives the output 0

Why is it so? Can’t grasp this logically at all. Can someone please
explain the behaviour here? Thanks in advance.

If you look up String#to_i, you will find that String#to_i actually
accepts an argument specifying the base to use.

When you have a space between the + operator and the two (+ 2), the
default argument for String#to_i is called. This is because the +
operator is not a valid argument and so Ruby knows that you are
actually adding the result of String#to_i.

However, when you don’t have a space between the + operator and the
two (+2), Ruby sees this as you specifying whether two is positive or
negative. Ergo, +2 becomes two (2) and it is supplied to String#to_i
as an argument.

Hmmmm, i see. Thanks a lot for your help!!!

i am try to change existing code,i am not unserstanding code,it is
written for blog archive clicking on each month and year in right column
it should redirect to that clicked month.by the below code only few are
working not all months,december is giving invalid date error
div class=“right-col”>

ARCHIVES


    <ul>
    <% archive_string = "" %>
    <% date_value = "" %>
  <% @posts_by_month.each do |monthname,                posts| %>

      <% date_value = (Date::MONTHNAMES[monthname[0..-6].to_i]) + "

" + (monthname[3…8]) %>
<% archive_string = “

  • <a class=‘filter’ href=’/blog?month=”
    • monthname[0…-6] + “&year=” + monthname[3…8] + “’>” + date_value +
    • ” + archive_string %>
      <% end %>
      <%= raw archive_string %>