Ruby,使得一些数字为负数

时间:2016-01-08 23:58:56

标签: ruby integer negative-number negative-integer

这可能是超级基本的,但我已经尝试了很多未能触及的东西..

我想将一个数字更改为它的否定版本。

answer = []
array = [3, 5, 2, 19, 2, 1]

array.each.with_index do |x, i|

   if x > array[i+1]
      answer << array[i] * -1
   else x =< array[i+1]
      answer << array[i] 
   end
 end
=> the answer I want is [-5] for when 'true' but I'm getting [5]

我也试过制作一个新的&#39; negarray&#39;将所有等效的负数作为&#39; array&#39;

answer = []
array = [3, 5, 2, 19, 2, 1]
negarray = [-3, -5, -2, -19, -2, -1]

=> again, getting [5], and not the [-5] I want. 

干杯!

3 个答案:

答案 0 :(得分:4)

在实际版本中,问题不明确。

如果你的意思是

  

我想将一个数字更改为它的否定版本。

你想要一个负数,然后你可以尝试:

answer = []
array = [3, 5, 6, 19, 2, 1]

array.each do |x|
   if x > 0
      answer << x * -1
   else
      answer << x 
   end
 end

 p answer

array.each do |x|
   answer << if x > 0
       x * -1
   else
       x 
   end
 end

或使用三元运算符:

array.each do |x|
   answer << (x > 0 ? -x : x)
 end

或更短且更红宝石的esk(使用三元运算符):

 array = [3, 5, 6, 19, 2, -1]
 answer = array.map { |n| n > 0 ? -n : n }

如果你喜欢更长的时间:

 answer = array.map do |n| 
  if n > 0 
    -n 
  else
    n 
  end
 end

如果您不想使用任何if结构,那么您可以使用负abs方法:

 answer = array.map { |n| -n.abs }

答案 1 :(得分:4)

以下一行

if x > array[i+1]

您基本上是在说明位置i处的元素是否大于i+1处的位置,您希望将其设为负数。问题是5小于下一个元素6,因此不会被否定。

让我们修复您的代码,并使用map方法来简化它:

out = array.map.with_index do |x, i|
   (array[i+1].nil? || x > array[i+1]) ? x : x*-1
end
# [-3, -5, -6, 19, 2, 1]

答案 2 :(得分:-1)

如果要在索引1处获取第二个数组元素的负值,请执行以下操作

<html>
    <head>

    <!-----------

EVENT PAGE by clumhood

:> ------------>

    <title>FANFIC RECS</title>
        <link rel="shortcut icon" href="{Favicon}">
        <link rel="alternate" type="application/rss+xml" href="{RSS}">
        <link rel="apple-touch-icon" href="{PortraitURL-128}"/>

        <link href='http://fonts.googleapis.com/css?family=Roboto:700,400' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

        <script type="text/javascript">
  WebFontConfig = {
    google: { families: [ 'Roboto:700,400:latin' ] }
  };
  (function() {
    var wf = document.createElement('script');
    wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
      '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
    wf.type = 'text/javascript';
    wf.async = 'true';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
  })(); </script>

  <!------- filter scripts -------->
 <script src="http://static.tumblr.com/fuu6t9w/kh8ml0pl9/jquery-1.7.1.min.js"></script>
 <script src="http://static.tumblr.com/fuu6t9w/eubml0pm0/jquery.isotope.min.js"></script>
 <script>
 $(function(){

 <!------- filter scripts -------->
 <script src="http://static.tumblr.com/fuu6t9w/kh8ml0pl9/jquery-1.7.1.min.js"></script>
 <script src="http://static.tumblr.com/fuu6t9w/eubml0pm0/jquery.isotope.min.js"></script>
 <script>
 $(function(){

 var $container = $('#container');

 $container.isotope({
 itemSelector : '.story'
 });


 var $optionSets = $('#sort .option-set'),
 $optionLinks = $optionSets.find('a');

 $optionLinks.click(function(){
 var $this = $(this);
 // don't proceed if already selected
 if ( $this.hasClass('selected') ) {
 return false;
 }
 var $optionSet = $this.parents('.option-set');
 $optionSet.find('.selected').removeClass('selected');
 $this.addClass('selected');

 // make option object dynamically, i.e. { filter: '.my-filter-class' }
 var options = {},
 key = $optionSet.attr('data-option-key'),
 value = $this.attr('data-option-filter');
 // parse 'false' as false boolean
 value = value === 'false' ? false : value;
 options[ key ] = value;
 if ( key === 'layoutMode' && typeof changeLayoutMode === 'function' ) {
 // changes in layout modes need extra logic
 changeLayoutMode( $this, options )
 } else {
 // otherwise, apply new options
 $container.isotope( options );
 }

 return false;
 });


 });
 </script>

 <!-----end filter scripts------>

 <!-----end filter scripts------>

        <style type="text/css">

body {
    font-family:arial;
    font-size:12px;
    background:#f8f8f8; /**this is the color of the bg.*/

}

a {
    color:#008997; /**this is the color of the links.*/
    text-decoration:none;
}

::-webkit-scrollbar {
background-color: white;
height:8px;
width:5px
}

::-webkit-scrollbar-thumb:vertical {
background-color:#f8f8f8;
height:50px
}

::-webkit-scrollbar-thumb:horizontal {
background-color:#505050;
height:8px!important
}


.top {
    text-align:left;
    padding-bottom:0px;
    margin-bottom:10px;
    margin-top:-9px;
    margin-left:-7px;
}


.top2 {
    width:1080px;
    background:white; /**this is the color of the filter titles topbar background.*/
    text-align:left;
    padding-bottom:0px;
    margin-bottom:10px;
    margin-top:10px;
    margin-left:-7px;
    line-height:20px;

}

#sort {
    padding:10px;
    text-align:center;
    font-family:'roboto', sans-serif;
    font-size:10px;
    text-transform:uppercase;
}

#sort a {
    margin-left:20px;
}

#sort a:hover {
    color:#bb2576; /**this is the color of the filter links when you hover over them.*/
}

.title {
    float:left;
    padding:15px;
    padding-top:20px;
    font-family:'roboto', sans-serif;
    font-size:12px;
    color:#bb2576;
    font-weight:normal;
}

.links {
    width:1100px;
    text-align:center;
    padding:30px;


}

.links a {
    font-family:'roboto', sans-serif;
    font-size:11px;
    text-transform:uppercase;
    padding:30px;
    margin-left:-3px;


}

.links a:hover {
    color:#b60079; /**this is the color of the links when you hover over them.*/

}

.links a:last-child {
}


#container {
    width:1080px;
    margin-top:10px;
}

#content {
    margin:10px;
    overflow:hidden;
    width:250px;
    height:250px;
    float:center;
    box-shadow:0px 3px 10px rgba(0,0,0,.15);
    text-align:left;
    line-height:150%;
    background:white; /**this is the color of the background of each event.*/
    transition-duration:1s;
    -moz-transition-duration:1s;
    -webkit-transition-duration:1s;
    -o-transition-duration:1s;
}



.desc {
    padding:10px;
    margin-top:10px;
    font-size:11px;
}


#content2 {
    margin:10px;
    overflow:hidden;
    width:250px;
    height:250px;
    float:left;
    box-shadow:0px 3px 10px rgba(0,0,0,.15);
    text-align:left;
    line-height:150%;
    background:#ffffff; /**this is the color of the background of each past event.*/
    transition-duration:1s;
    -moz-transition-duration:1s;
    -webkit-transition-duration:1s;
    -o-transition-duration:1s;
}

        </style>
        </head>

    <body>

要将数组的所有值更改为负数,请使用以下

answer << array[1] * -1